开发者

Assignment operator on only one of two parents

Child has two parents: Foo and Bar. Foo does not allow copying. Bar does. How can Child use Bar's assignment operator to copy into Bar's subset of Child (while leaving Foo's subset intact)?

To be more concrete: in the code below, how can Child refer to just Bar inside replace_bar()? (How would you modify line (X) to make the code compile?)

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;           //开发者_如何学Python line (X)
    }
};

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


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

In other news, you're missing a return *this; in Bar::operator= and if all you want to do is prevent copy of Foo you shouldn't define the copy constructor and assignment operator, only declare them. That way even if you try to use them from within the class you'll get an error (albeit a link error not a compile error).

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜