【发布时间】:2015-05-20 07:48:05
【问题描述】:
我是这样维护三人法则的--
// actual constructor
stuff::stuff(const string &s)
{
this->s_val = s[0];
this->e_val = s[s.length() - 1];
}
// copy constructor
stuff::stuff(const stuff &other)
{
this->s_val = other.s_val ;
this->e_val = other.e_val ;
}
// assignment
stuff& stuff::operator=(const stuff &other)
{
stuff temp(other);
*this = move(temp);
return *this;
}
现在我可以这样打电话了--
stuff s1("abc");
stuff s2(s1);
stuff s3 = s2 ; // etc ...
现在我正在尝试实现一个将使用 operator= 的函数,以便我可以像这样调用 --
stuff s;
s = "bcd" ;
我是这样写的——
stuff& stuff::operator=(const string &s)
{
stuff temp(s);
*this = move(temp);
return *this;
}
但它给了我段错误。此外,如果想打电话我该怎么办
stuff s = "bcd" ?
我该怎么做?
【问题讨论】:
-
*this = move(temp);正在调用您尝试定义的赋值运算符。 -
我明白了,它是在进行递归调用吗?
-
是的,确实如此。
-
等一下,但我的
operator=()有一个string参数,而不是stuff,那么为什么它不在stuff& stuff::operator=(const stuff &other)中进行递归调用? -
你的另一个
operator=。带有递归调用的那个(除非你有移动赋值,但你没有展示出来。)无论如何,你真的需要实现特殊的成员函数吗?如果是这样,请显示足够的代码来证明您这样做。
标签: c++ c++11 constructor operator-overloading