切割问题(splicing)……

underuwing 2009-11-18 09:34:31
在Effective c++,中文第三版第89页看到的。切割问题:值传递方式传递参数时,用子类对象的实参传递给父类对象的形参时会丢失子类对象的特性,叫切割。书中的解决办法是通过reference-to-const来解决。我试了一下,编译都没通过,不知道为什么?
#include <iostream>
#include <string>
using namespace std;
class father
{
public:
father(string sName):name(sName){}
virtual void display()
{
cout<<"this is father class";
}
void print()
{
cout<<name;
}
private:
string name;
};
class son: public father
{
public:
son(string ssName):father(ssName){}
void display()
{
cout<<"this is son class";
}
};
void printAndDisplay(const father& x)
{
x.display();
}
int main()
{
son s1("jack");
printAndDisplay(s1);
}

提示出错: 不能将“this”指针从“const father”转换为“father &”。
...全文
166 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
lori227 2009-11-19
  • 打赏
  • 举报
回复
printAndDisplay(const father& x)
{
x.display();//const 的对象只能调用类中的const 函数。。。 display()不是const
}

64,648

社区成员

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

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