创建用C类赋值(=)运算符++
Possible Duplicate:
Operator overloading创建用C类赋值(=)运算符++
EDIT 2
我用刀片(...)不正确,我没有实际需要 '=' 运算符。抱歉浪费人们的时间。我已投票结束..仍然有2票。请投票。
EDIT
我想要一个“=”操作符是这样我可以使用插入物(...)函数上推导对象的矢量的原因。此刻我的编译器说:
/usr/include/c++/4.2.1/bits/stl_algobase.h:283: error: no match for 'operator=' in '* __result = * __first'
我创建“==”和“<”为我自己的类运营商之前,但我竭力要打造一个“=”运算符。我的阶级是这样的(忽略傻变量名):
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
// ...
};
,我想知道我需要把
// What do '=' return? An object of the class right?
Derivation& operator=(const Derivation &d) const {
// something....
}
非常感谢。
这取决于你,真的。你需要运营商做什么?你想返回一个参考,还是你想要一个副本?
编辑:请注意,这是修辞。你使用这个矢量将决定你是否需要一个引用或一个副本。例如,如果插入的对象在从矢量中移除之前就会超出范围,那么您需要一个副本。如果不是,并且希望在更改向量中的实例时生成原始对象,则需要引用。希望有点帮助。
自 - @jalf尚未提出了一个答案,这里是:)
Derivation& operator=(const Derivation &d) {
// something....
return *this;
}
你需要一个参考返回这个实例。 this
是一个关键字,它包含一个指向操作员所在实例的指针。
先删除常量... 然后如果你真的需要一个拷贝操作,做这样的事情,并添加自己的逻辑(所以它不会做到这正是将与编译器生成的拷贝操作来完成):
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;
}
除了这是***正是***编译器生成的复制赋值运算符所做的...... –
@Armen - 真的吗?我没有意识到编译器生成的赋值运算符也会调用'vector'成员的赋值? – Nim
首先,赋值运算符可能不应该const--
其次,赋值运算符通常会返回一个非const引用到被分配一个值(*此)
实现赋值运算符的标准方法是复制和交换。 这样做的好处在于,可以使得赋值运算符在异常和自赋值时正确无误。它还根据复制构造函数定义了赋值操作,因此如果向该类添加额外成员,则可以减少代码需要更改的位置数。
反正 - 这里是什么样子,你的情况:
class Derivation {
public:
string rc;
ImplementationChoice Y;
vector<Derivation> X;
vector<string> D;
vector<string> C;
vector<Player> P, O;
vector<Attack> B;
//You need to add a swap function to your class
void swap(Derivation& o) {
rc.swap(o.rc);
Y.swap(o.Y);//Assuming ImplementationChoice has a swap function (it should!)
X.swap(o.X);
D.swap(o.D);
C.swap(o.C);
P.swap(o.P);
O.swap(o.O);
B.swap(o.B);
}
Derivation& operator=(Derivation const& o) {
Derivation copy(o);
copy.swap(*this);
return *this;
}
// various functions
// ...
};
最起码,它应该返回一个引用('推导&'),而不是对象的新副本。 :) – jalf
谢谢..现在编辑帖子。对不起。对C++来说很新颖 – ale
我建议你阅读[运算符重载常见问题](http://stackoverflow.com/q/4421706/46642)。 –