首页 > 解决方案 > 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)?

标签: c++oop

解决方案


推荐阅读