复制构造函数和重载' ='操作员不工作

时间:2015-07-09 08:06:27

标签: c++11 copy-constructor assignment-operator

复制构造函数和重载' ='当分配了两个类对象的和的结果时,不调用operator。初始化并分配单个对象时,工作正常。错误说"'operator ='不匹配(操作数类型是'comp'和'comp')"。重要的代码片段是

#include <iostream>
#include <map>
#include <string>

using namespace std;

struct Grades {
    string             id;       // student ID, e.g,, a12345678
    map<string, int> scores;     // course, score, e.g. COMP3512, 86
};


ostream& operator<<(ostream& os, const Grades g) { 
    os << g.id << endl << g.scores.size() << endl;
    for (auto it = g.scores.begin(); it != g.scores.end(); ++it) 
        os << (*it).first << ' ' << (*it).second << endl;
    return os;
}

int main(int argc, char** argv)
{
    Grades g;
    g.id = "a12345678";
    g.scores["COMP3512"] = 87;
    g.scores["COMP3760 "] = 68;
    cout << g;
    return 0;
}

2 个答案:

答案 0 :(得分:2)

让我们走这条线

>>> json.dumps([{"method": "do_thing", "params": [1], "jsonrpc": "2.0"},  {"method": "do_thing", "params": [1+1], "jsonrpc": "2.0"}])
'[{"jsonrpc": "2.0", "params": [1], "method": "do_thing"}, {"jsonrpc": "2.0", "params": [2], "method": "do_thing"}]'

db.joined.find();操作返回一个临时对象。但是,非常量引用不能绑定到临时对象,并且copy-constructor将其参数作为非常量引用。

修复很简单,更改复制构造函数和复制赋值运算符,将其参数作为常量引用,例如。

comp c4=c3+c1;

请注意,在例如中使用非常量引用参数复制构造函数仍然可以使用它,你只需要将实际的非临时对象传递给它,比如

c3+c1

答案 1 :(得分:0)

默认情况下,会优化一些复制操作。要确保不使用复制优化,您应该使用正确的编译器标志。对于gcc,请尝试使用:-no-eligible-constructors