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

C++ 具有派生类型参数的赋值运算符,c++,inheritance,operator-overloading,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; } 由于B::operato

这会导致编译错误:

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;
}
由于B::operator=(A&)具有非标准签名,编译器将生成自己的B::operator=(B&),它(尝试)调用私有的A::operator(A&)


有没有办法让编译器也对B参数使用B::operator=(A&)呢?

当然。只需自己定义操作符并将调用转发到
operator=(const A&)

B类:公共A类{
公众:
运算符=(常数A&){
归还*这个;
}
B和运算符=(常量B和其他){
return*this=static_cast(其他);
}
};

这个问题是一个C++概念,我联想到一个坏概念嗅觉。< /P> 你的问题可能是一个错误的问题,而且,没有完美的解决方案。尽你所能,在所实施的解决方案中总会出现一些错误

下面是这个重复问题的(稍微)完整答案:


顺便说一句,如果赋值操作符是私有的,这就清楚地表明基类的作者非常清楚实体语义和值语义不能很好地混合。相信他,他是对的

我认为尝试对继承的类型使用运算符重载是个坏主意。 在C++中,我建议您为每个受支持类型明确地提供函数,当涉及操作符重载时。

不久前我自己也掉进了这个陷阱。如果您想了解C++用户如何使用这个特性,我建议您查看<代码> STD::向量 也许上述答案可以帮助您解决这个问题:

另一个可能的解决办法是:

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

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

我也是基类的作者。我想做的是拥有一个不可变的基类,并在派生类中添加“mutating”函数。因为运算符=()的rhs是只读的,所以将参数作为基类的引用是有意义的。
class B : public A {
public:
    B& operator=(const A&) {
            return *this;
    }

    B& operator=(const B& other) {
        return *this = static_cast<const A&>(other);
    }
};
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;
}