首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

虚函数与重载解决方法

2012-04-20 
虚函数与重载这个是《C++ Primer Plus》中文第五版475页的第四题,有如下定义的基类和派生类C/C++ codeclass

虚函数与重载
这个是《C++ Primer Plus》中文第五版475页的第四题,有如下定义的基类和派生类

C/C++ code
class Port{private:    char * brand;    char style[20];             // i.e., tawny, ruby, vintage    int bottles;public:    Port(const char * br = "one", const char * st = "one", int b = 0);    Port(const Port & p);     // copy constructor    virtual ~Port() { delete [] brand; }    Port & operator=(const Port & p);    Port & operator+=(int b); // adds b to bottles    Port & operator-=(int b); // subtracts b from bottles, if    int BottleCount() const { return bottles; }    virtual void Show() const;    friend ostream & operator<<(ostream & os, const Port & p);};class VintagePort : public Port // style necessarily = “vintage”{private:    char * nickname;            // i.e., “The Noble” or “Old Velvet”, etc.    int year;                    // vintage yearpublic:    VintagePort();    VintagePort(const char * br, int b, const char * nn, int y);    VintagePort(const VintagePort & vp);    ~VintagePort() { delete [] nickname; }    VintagePort & operator=(const VintagePort & vp);    void Show() const;    friend ostream & operator<<(ostream & os, const VintagePort & vp);};

问题:
3.解释为何没有将 operator= 和 operator<< 声明为虚拟?

求解答!以下是这个问题的原文




[解决办法]
解释为何没有将 operator= 和 operator<< 声明为虚拟?

operator=属于特殊的成员函数不能被声明为virtual。而友元operator<<根本就不是成员函数所以就更不可能是声明为虚函数了。
[解决办法]
虚函数要求函数除了名称一样,参数也要一样.
operator= 和 operator<< 这些对不同的类参数是不一样的:
Port & operator=(const Port & p);
VintagePort & operator=(const VintagePort & vp);
这个两个的参数和返回值类型都不一样
[解决办法]
operator= 和 operator<< 是不需要重载的,所以就不虚拟了
[解决办法]
operator=类似构造函数一样不能虚构,operator<<这里是友元函数,不是成员函数,不能虚构。

热点排行