struct Base
{
double x{ 111.1 };
};
struct Derive :public Base
{
double y{ 222.2 };
Derive& operator=(const Derive& obj)
{
if (&obj == this)
{
return *this;
}
Base::operator=(obj); // 显示调用基类operator=
// 酌情处理自赋值的问题
y = obj.y;
return *this;
}
};
int main()
{
Derive d;
d.x = 1.1;
d.y = 2.2;
Derive d1;
d1.x = 3.3;
d1.y = 5.5;
d = d1;
cout << d.x << '\n'; // 若不显示调用基类operator=,还是1.1
cout << d.y << '\n'; //
system("pause");
return EXIT_SUCCESS;
}
输出:
3.3
5.5
参考:《C++ Primer》 P555
标签:Derive,obj,C++,运算符,Base,派生类,operator,d1 From: https://www.cnblogs.com/huvjie/p/18414829