虚函数与重载

pp25210 2012-04-05 01:26:35
这个是《C++ Primer Plus》中文第五版475页的第四题,有如下定义的基类和派生类

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 year
public:
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<< 声明为虚拟?

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


...全文
224 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cattycat 2012-04-05
  • 打赏
  • 举报
回复
operator=类似构造函数一样不能虚构,operator<<这里是友元函数,不是成员函数,不能虚构。
深圳大哥 2012-04-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

解释为何没有将 operator= 和 operator<< 声明为虚拟?

operator=属于特殊的成员函数不能被声明为virtual。而友元operator<<根本就不是成员函数所以就更不可能是声明为虚函数了。
[/Quote]


这个好像是C++ Primer的原话哈,值得接受
luochao7050838 2012-04-05
  • 打赏
  • 举报
回复
operator= 和 operator<< 是不需要重载的,所以就不虚拟了
www_adintr_com 2012-04-05
  • 打赏
  • 举报
回复
虚函数要求函数除了名称一样,参数也要一样.
operator= 和 operator<< 这些对不同的类参数是不一样的:
Port & operator=(const Port & p);
VintagePort & operator=(const VintagePort & vp);
这个两个的参数和返回值类型都不一样
pengzhixi 2012-04-05
  • 打赏
  • 举报
回复
解释为何没有将 operator= 和 operator<< 声明为虚拟?

operator=属于特殊的成员函数不能被声明为virtual。而友元operator<<根本就不是成员函数所以就更不可能是声明为虚函数了。

64,281

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧