假设我有以下内容:
class A
{
public:
A& operator= (A const& other)
{
return *this;
}
};
class B : public A
{
public:
B& operator= (B const& other)
{
static_cast<A&>(*this) = static_cast<A const&>(other);
// or...
A::operator=(other);
return *this;
}
};
要调用A
副本分配运算符的版本,我可以执行以下任一操作:
static_cast<A&>(*this) = static_cast<A const&>(other);
或者:
A::operator=(other);
为什么要选择一个?两者之间有什么区别?
我的问题的最初示例是无效的,并且与我要问的问题相去甚远。我为这个错误表示歉意。我已经更新了上面的示例,使其更加清晰。
static_cast<A&>(*this).foo()
仍调用的派生版本foo
。这只是通过基类引用调用虚函数。
而A::foo()
关闭虚拟调度和调用是foo
在class中实现的A
,而不是在派生类中实现。
如果operator=
in中不是virtual A
,static_cast<A&>(*this) = static_cast<A const&>(other)
则是另一种说法A::operator=(other)
(无需other
转换,因为派生的基准引用转换是隐式的)。他们做同样的事情-打电话A::operator=
。
但是,通常operator=
是在复制构造函数之后再进行交换的情况下实现的:
B& B::operator=(B other) {
other.swap(*this);
return *this;
}
以B
按价值计算所调用B
的拷贝构造函数我们。如果B
具有r值复制构造函数,则该赋值运算符可与r值以及仅移动B
(B
例如,如果具有std::unique_ptr
成员)一起使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句