Creating an assignment (=) operator for class in C++
Possible Duplicate:
Operator overloading
EDIT 2
I was using insert(...) incorrectly, I didn't actually need a '=' operator. Sorry to waste peoples' time. I have voted to close.. 2 votes remain. Please vote.
EDIT
The reason I want an '=' operator is so I can use the insert(...) function on a vector of Derivation objects. At the moment my compiler says:
/usr/include/c++/4.2.1/bits/stl_algobase.h:283: error: no match for 'operator=' in '* __result = * __first'
I have created '==' and '<' operators for my own classes before but I'm struggling to create an '=' operator. My class looks like this (ignore the silly variable names):
class Derivation {
public:
string rc;
ImplementationChoice Y;
vector<Derivation> X;
vector<string> D;
vector<string> C;
vector<Player> P, O;
vector<Attack> B;
// various functions
// ...
};
and I want to know what I need to put in
// What do '=' return? An object of the class right?
Derivation& operator=(const Derivation &d) const {
// something....
}
Many thanks.
First, an assignment operator probably should not be const--
Second, assignment operators usually return a non-const reference to the object that was assigned a value (*this)
You don't need one. The compiler-generated one will do just fine.
首先删除const ...然后如果你真的需要一个复制操作符 ,那么做一些类似的事情并添加你自己的逻辑(这样它就不会完全做到编译器生成的复制操作符会做什么):
Derivation& operator=(const Derivation& other) {
this->rc = other.rc;
this->Y = other.Y;
this->X = other.X;
this->D = other.D;
this->C = other.C;
this->P = other.P;
this->O = other.O;
this->B = other.B;
// ...
return *this;
}
链接地址: http://www.djcxy.com/p/12706.html
上一篇: C ++运算符==重载
下一篇: 在C ++中为类创建赋值(=)运算符