c++ - 只有两个 parent 之一的赋值运算符

标签 c++ operator-overloading multiple-inheritance assignment-operator

child 有两个 parent :Foo 和 Bar。 Foo 不允许复制。酒吧有。 Child 如何使用 Bar 的赋值运算符复制到 Bar 的 Child 子集(同时保持 Foo 的子集完好无损)?

更具体地说:在下面的代码中,Child 如何在 replace_bar() 中仅引用 Bar? (您将如何修改第 (X) 行以使代码通过编译?)

class Foo
{
public:
    Foo () {}
private:
    Foo (const Foo & f) {} // forbid copy construction
    Foo & operator= (const Foo & foo) {} // forbid assignment
};

class Bar
{
public:
    Bar () {}
    Bar & operator= (const Bar & bar) {}
};

class Child : public Foo, public Bar
{
public:
    Child () {}
    void replace_bar (const Bar & bar2)
    {
        *this = bar2;           // line (X)
    }
};

int main ()
{
    Child child;
    Bar newbar;
    child.replace_bar (newbar);
}

最佳答案

void replace_bar(const Bar& bar2) {
     Bar::operator=(bar2);
}

在其他消息中,您在 Bar::operator= 中缺少 return *this; 并且如果您只想防止复制 Foo 你不应该定义复制构造函数和赋值运算符,只声明它们。这样即使您尝试从类中使用它们,您也会收到错误(尽管是链接错误而不是编译错误)。

class Foo {
    Foo(const Foo&); // no body
    Foo& operator=(const Foo&); // ditto
public: 
    Foo() { }
};

关于c++ - 只有两个 parent 之一的赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272991/

相关文章:

java - 阐明多重继承的概念 : Can a diamond structure issue occur?

c++ - 自动端口转发(UPnP?)C++

c++ STL容器存储了一个重载operator =的类

c++ - 帮助理解 C++、模板、operator() 的类示例代码

c++ - 嵌入式 C++ 编译器不支持多重继承的实例?

c++ - 没有 RTTI 的 dynamic_cast

c++ - getrusage对我不起作用吗?为什么?

c++ - 内联函数,内部类,C++

c++ - 如何解释以下 C(包括位字段和结构)

c++ - 在 C++ 中使用自定义字符串类作为映射键值