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

标签 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;
}

这会导致编译错误:

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

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

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

最佳答案

当然。只需自己定义运算符并将调用转发给 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);
    }
};

关于c++ - 具有派生类型参数的赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7358134/

相关文章:

Swift - 如何添加扩展具有新属性的现有类?

javascript - 子类继承父类(super class)属性

python-2.7 - 为什么有些操作符在 Odoo 中的记录集没有按预期工作?

c++ - 使用 map 容器创建矩阵

c++ - 是否可以在头文件中重载运算符(在声明类时)?

c++ - 读取和写入文件 C++

c++ - 字符串二进制组合

c++ - 虚函数被覆盖且私有(private),公共(public)说明符

c++ - 将 char* 严格别名为更广泛的类型,没有未定义的行为

python - 何时使用关联、聚合、组合和继承?