c++ - C++ 运算符多态性
问题描述
考虑以下 C++ 简单程序。
#include<iostream>
class Rectangle {
protected:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {};
Rectangle operator*(double m, const Rectangle & R) {
return Rectangle(R.width * m, R.height * m);
}
void display(){std::cout<<"Rect : "<<width<< ":"<<height<<std::endl;};
};
class Square : public Rectangle {
public:
Square(double c) : Rectangle(c, c) {};
Square(const Square & c) : Rectangle(c) {};
Square(Rectangle const &other):Rectangle(other) {};
void display(){std::cout<<"Square : "<<width<< ":"<<height<<std::endl;};
};
int main(int argc, char * argv[]) {
Rectangle r1(2, 3);
Rectangle r2 = 2 * r1; // Working as it should
Square c1(5);
Square c2 = (2 * c1); // Also working
Square c3 = (2 * r1); // But this also working :(
r1.display();
r2.display();
c1.display();
c2.display();
c3.display();
return 0;
}
问题:最好是在 Square 类中重载运算符 * (即两次编写相同的代码)还是像在示例中那样使用专用的复制构造函数(但 Square 可能包含 Rectangle)?
解决方案
推荐阅读
- python - 如何“旋转”交换 matplotlib.pyplot.imshow 轴
- powerbi - 计算列和度量之间有什么区别?
- javascript - 三元运算符中的三元运算符是否可能
- java - 保持双向一对多关联同步
- automated-tests - 无法读取未定义的属性“$”
- loops - 为什么这段代码的时间复杂度是 O(n) 而不是 O(log n)
- css - 我怎样才能摆脱表格中每 5 行的边框底部较厚的事实?
- c++ - 为什么 AVR-GCC 编译器在使用相同的变量但作为 PROGMEM 重载时会引发错误?
- java - Android Java 获取所有后台运行的应用程序或服务
- wordpress - 我的 Elementor pro 没有在我的 Genesis 主题上工作