我想在派生的类中制作" "运算符时,我会有一些问题。我的基课上已经有一个" " Oparator。
class Base{
//Some data
public:
//Some other function
Base operator+(const Base& rhs_s) const ;
Base operator+(char rhs_c) const { return *this + Base(rhs_c);}
//Some other function
};
class Derived :public Base{
public:
Derived () :Base("") {}
Derived (char c) :Base(c) {}
Derived (const char* c) :Base(c) {}
Derived operator+(const Derived& s) const {
return Derived(*this) + Derived(s);
}
所以我不能添加两个变量,其中"派生 'c'"
我感谢您的帮助
使用您的代码,我可以做到这一点:
Derived d{'c'};
const Derived d2 = d + 'C';
您在评论中的示例不同:
const Base d("hello");
Derived b;
b = d + 'C';
上面的代码不会编译,因为将返回基本对象,该对象无法隐式升起到派生类型。例如:
Derived d;
Base b = d; // This is fine because you are going from a more specific type to a less specific one
Derived d2 = b; // This is not okay unless you explicitly define an assignment/constructor for Derived that takes a Base object