我有以下代码:
#include <iostream>
using namespace std;
class Base {
public:
Base operator/(const Base& other){
Base res;
cout << "Base /" << endl;
return res;
}
Base& operator/=(const Base& other){
cout << "Base /=" << endl;
return *this;
}
};
class Derived : public Base {
public:
Derived operator/(const Derived& other){
Derived res;
cout << "Derived /" << endl;
return res;
}
};
int main() {
Derived d1, d2;
Base b1, b2;
b1 = d1 / d2;
b2 = d1 /= d2;
}
第二项作业输出Base /=
。我是否可以实现使用被覆盖的operator/
的第二项任务,而不会覆盖operator/=
?我想我必须使用另一个来实现一个运算符。
这是一个家庭作业,所以只提供基本想法可以做什么。
答案 0 :(得分:0)
虽然显然不是首选的方式,可能是某些&#34;丑陋的&#34;,但可以在不提供Derived::operator/
的情况下使用Derived::operator/=
。为此,需要执行以下步骤:
/
Base::operator/=
/
设为虚拟,使其在/=
中不受静态约束 - 实现operator/
中提供Derived
- 实施,覆盖Base
中的实施,即除了virtual Base operator/(const Base&)
之外还提供运营商Derived operator/(const Derived&)
(注意后者无法覆盖,因为它有一个协变参数类型)Derived::operator/(const Base& other)
- 实施中,检查other
的动态类型并明确调用相应的实现。请参阅以下代码:
class Base {
public:
virtual Base operator/(const Base& other) const {
Base res;
cout << "Base /" << endl;
return res;
}
Base& operator/=(const Base& other){
cout << "Base /=" << endl;
*this = *this / other;
return *this;
}
};
class Derived : public Base {
public:
virtual Base operator/(const Base& other) const override {
cout << "Derived /(Base&)" << endl;
if(dynamic_cast<const Derived*>(&other)==0) {
// do something specific here, or call base operator:
return Base::operator/(other);
}
else {
return operator/(dynamic_cast<const Derived&>(other));
}
}
Derived operator/(const Derived& other) const { // cannot override
cout << "Derived /(Derived&)" << endl;
return *this;
}
};
int main() {
Derived d1, d2;
Base b1, b2;
b1 = d1 / d2;
// Output: Derived /(Derived&)
b2 = d1 /= d2;
// Output:
// Base /=
// Derived /(Base&)
// Derived /(Derived&)
return 0;
}
请注意,表达式Derived d3 = d2 /= d1
仍然无法使用,因为运算符Base &
的返回类型Base& Base::operator /=
无法转换为Derived &
。