开发者

Assignment operator with derived type argument

开发者 https://www.devze.com 2023-04-03 21:39 出处:网络
class A { private: A& operator=(const A&); }; class B : public A { public: B& operator=(const A&) {
class A {
private:
    A& operator=(const A&);
};

class B : public A {
public:
    B& operator=(const A&) {
            return *this;
    }
};


int main() {

    B b1;
    B b2;

    b1 = b2;

    return 0;
}

This gives error on compilaton:

test.cpp: In member function 'B& B::operator=(const B&am开发者_如何学编程p;)':
test.cpp:16:5: error: 'A& A::operator=(const A&)' is private
test.cpp:19:20: error: within this context
test.cpp: In function 'int main()':
test.cpp:31:7: note: synthesized method 'B& B::operator=(const B&)'
first required here 
Build error occurred, build is stopped

Since B::operator=(A&) has a non-standard signature, the compiler generates it's own B::operator=(B&) which (tries) to call A::operator(A&), which is private.

Is there any way I can get the compiler to use B::operator=(A&) also for B arguments?


Sure. Just define the operator yourself and forward the call to operator=(const A&).

class B : public A {
public:
    B& operator=(const A&) {
            return *this;
    }

    B& operator=(const B& other) {
        return *this = static_cast<const A&>(other);
    }
};


This problem is a C++ gotcha that I associate to a bad conception smell.

Your problem is likely a false problem, to which, furthermore, there is no perfect solution. Try as hard as you wish to, there will always be something wrong in the solution implemented.

Here is a (little) more complete answer to this duplicate question: How to use base class's constructors and assignment operator in C++?

BTW, if the assignment operator is private, this is a clear sign that the author of the base class knew very well that entity semantics and value semantics don't mix well. Trust him, he was right!


I think it's a bad idea to try to use operator overloading with inherited types. In C++ I recommend you to explicitly provide functions for each supported type, when it comes to operator overloading.

I went into this trap myself not too long ago. If you want to look into how experienced c++ people use this feature I recommend you to look into the template specialization of std::vector<bool>.

Maybe above answer may help you to tackle this problem: C++ Abstract class operator overloading and interface enforcement question

Another possible solution would be:

class B {
public:
  B& operator=(const A&) {
    return *this;
  }
};

class A {
private:
  A& operator=(const A&);
public:
  operator B() { /* do stuff to convert from A to B */ }
};

int main() {

  B b1;
  B b2;

  b1 = b2;

  return 0;
}
0

精彩评论

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

关注公众号