上面的问题解决了。但是当我包含一个头文件后,代码又不能编译出错了
Sales_data.h
程序代码:
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <iostream>
#include <string>
class Sales_data
{
friend std::istream& read(std::istream&, Sales_data&);
friend std::ostream& print(std::ostream&, const Sales_data&);
friend Sales_data add(const Sales_data&, const Sales_data&);
public:
Sales_data() : Sales_data("", 0, 0.0) { std::cout << "Sales_data()" << std::endl; }
Sales_data(std::string& s) :Sales_data(s, 0, 0.0) { std::cout << "Sales_data(std::string &)" << std::endl; }
Sales_data(std::string s, unsigned n, double p) :bookNo(s), units_sold(n), revenue(n* p) { std::cout << "Sales_data(std::string &,unsigned n,double p)" << std::endl; }
Sales_data(std::istream& is) : Sales_data("", 0, 0.0) { read(is, *this); }
std::string isbn() const { return bookNo; }
Sales_data& combine(const Sales_data&);
double avg_price() const;
private:
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
std::istream& read(std::istream&, Sales_data&);
std::ostream& print(std::ostream&, const Sales_data&);
Sales_data add(const Sales_data&, const Sales_data&);
#endif
exercise.cpp
程序代码:
#include <map>
#include <functional>
#include <iostream>
#include <string>
#include "Sales_data.h"
using namespace std;
int add(int i, int j)
{
return i + j;
}
int half(int i)
{
return i / 2;
}
int main()
{
map<string, function<int(int, int)>> binops = {
{"+",add},
{"-",minus<int>()},
{"*",[](int i,int j) { return i * j; }},
{"/",[](int i,int j) { return i / j; }}
};
map<string, int(*)(int, int)> binops2 =
{
{"+",add}
};
function<int(int, int)> fn3 = add;
function<int(int)> fn1 = half;
function<int(int)> fn2 = ½
cout << fn1(60) << endl;
return 0;
}
提示:error C2440: 'initializing': cannot convert from 'initializer list' to 'std::map<std::string,std::function<int (int,int)>,std::less<std::string>,std::allocator<std::pair<const std::string,std::function<int (int,int)>>>>'
[此贴子已经被作者于2023-5-17 14:37编辑过]