具有派生类型参数的赋值运算符

Pib*_*ben 2 c++ inheritance operator-overloading

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;
}
Run Code Online (Sandbox Code Playgroud)

这给compilaton带来错误:

test.cpp: In member function 'B& B::operator=(const B&)':
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
Run Code Online (Sandbox Code Playgroud)

由于B :: operator =(A&)具有非标准签名,编译器会生成它自己的B :: operator =(B&),它(尝试)调用A :: operator(A&),这是私有的.

有什么方法可以让编译器对B参数使用B :: operator =(A&)吗?

Jon*_*Jon 7

当然.只需自己定义操作员并将呼叫转发给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);
    }
};
Run Code Online (Sandbox Code Playgroud)