声明期间的 C++ 赋值运算符
C++ assignment operator during declaration
这是我的 class Hero,有两个重载赋值运算符 - Hero 到 Hero 和 String 到 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<<"\n";
}
const Hero &operator =(const Hero &other){
std::cout<<"Overloaded Assignment class to class! \n";
x = other.x;
name = other.name;
return *this;
}
const Hero &operator =(const std::string N){
std::cout<<"Overloaded Assignment from string! \n";
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! \n";
zak = bar; //"Overloaded Assignment class to class! \n";
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);
这是 copy-initialization 并且因此调用 copy-constructor.
的问题
Hero bar = "HelloWorld";
是否等同于:
Hero bar = Hero("HelloWorld");
这又相当于:
Hero bar(Hero("HelloWorld"));
并且由于您没有 Hero("HelloWorld")
的构造函数,因此它是无效的。
这是我的 class Hero,有两个重载赋值运算符 - Hero 到 Hero 和 String 到 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<<"\n";
}
const Hero &operator =(const Hero &other){
std::cout<<"Overloaded Assignment class to class! \n";
x = other.x;
name = other.name;
return *this;
}
const Hero &operator =(const std::string N){
std::cout<<"Overloaded Assignment from string! \n";
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! \n";
zak = bar; //"Overloaded Assignment class to class! \n";
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);
这是 copy-initialization 并且因此调用 copy-constructor.
的问题
Hero bar = "HelloWorld";
是否等同于:
Hero bar = Hero("HelloWorld");
这又相当于:
Hero bar(Hero("HelloWorld"));
并且由于您没有 Hero("HelloWorld")
的构造函数,因此它是无效的。