在来自此链接的问题的最佳评价答案中,我不明白派生赋值运算符如何从基类调用赋值运算符,即在这部分代码中:
Derived& operator=(const Derived& d)
{
Base::operator=(d);
additional_ = d.additional_;
return *this;
}
做什么
Base::operator=(d)
意思是?它有什么作用?干杯!
在来自此链接的问题的最佳评价答案中,我不明白派生赋值运算符如何从基类调用赋值运算符,即在这部分代码中:
Derived& operator=(const Derived& d)
{
Base::operator=(d);
additional_ = d.additional_;
return *this;
}
做什么
Base::operator=(d)
意思是?它有什么作用?干杯!
Base::operator=
调用Base
类版本operator=
来复制对象的一部分,Base
然后派生类复制其余部分。由于基类已经正确完成了所有需要的工作,为什么要重复工作,只需重用即可。所以让我们看这个简化的例子:
class Base
{
std::string
s1 ;
int
i1 ;
public:
Base& operator =( const Base& b) // method #1
{
// trvial probably not good practice example
s1 = b.s1 ;
i1 = b.i1 ;
return *this ;
}
} ;
class Derived : Base
{
double
d1 ;
public:
Derived& operator =(const Derived& d ) // method #2
{
// trvial probably not good practice example
Base::operator=(d) ;
d1 = d.d1 ;
return *this ;
}
} ;
Derived
将有三个成员变量,两个来自Base
:s1
和i1
一个它自己的d1
。所以Base::operator=
称我标记为的内容复制了继承自哪个method #1
的两个变量是和,因此剩下要复制的就是哪个负责。Derived
Base
s1
i1
d1
method #2
它只是对当前对象的成员函数的调用。当前对象继承了一个完全限定名称为 的函数Base::operator=
,您可以像调用任何其他非静态成员函数一样调用它。