声明期间的C++赋值运算符
这是我的类Hero,具有两个重载赋值运算符-Hero to Hero和String to Hero。
#include <iostream>
class Hero {
private:
int x;
std::string name;
public:
Hero():x(42), name("JohnDoe") {};
Hero(int a, std::string b):x(a), name(b) {};
void print(){
std::cout<<name<<" : "<<x<<"
";
}
const Hero &operator =(const Hero &other){
std::cout<<"Overloaded Assignment class to class!
";
x = other.x;
name = other.name;
return *this;
}
const Hero &operator =(const std::string N){
std::cout<<"Overloaded Assignment from string!
";
x = 777;
name = N;
return *this;
}
};
int main(){
Hero foo(42, "Hercules");
Hero zak = foo; // Regular assignmnet, not the overloaded
// Hero bar = "HelloWorld"; <<<< Illegal
Hero zoo(HelloWorld",42); << Ok, but here we use constructor, not an assignment operator
Hero bar;
bar = "Ayax"; // "Overloaded Assignment from string!
";
zak = bar; //"Overloaded Assignment class to class!
";
zak.print();
bar.print();
}
和产生的结果:
Overloaded Assignment from string!
Overloaded Assignment class to class!
Ayax : 777
Ayax : 777
为什么不能在声明中使用重载运算符进行变量初始化?
行Hero zak = foo;
编译器使用非重载运算符,字符串Hero bar = "HelloWorld"
是非法的。
解决方案
在定义时初始化对象时,即使使用=
语法,它也没有使用赋值。
当您这样做时:
Hero zak = foo;
相当于:
Hero zak(foo);
这是复制初始化,因此调用复制构造函数。
的问题
Hero bar = "HelloWorld";
它等同于:
Hero bar = Hero("HelloWorld");
这又相当于:
Hero bar(Hero("HelloWorld"));
由于您没有Hero("HelloWorld")
的构造函数,因此它无效。
相关文章