c++ - 方法覆盖没有按预期工作
问题描述
对不起,如果标题不是很好,我想不出别的了
我得到了这个程序:
class Animal
{
private:
int legs;
string sound;
protected:
Animal(int l, string s) : legs(l), sound(s) {}
public:
Animal() {}
string getClass()
{
return "Animal";
}
void printInfo()
{
cout <<"This is a(n) "<<getClass()<<". It has "<<getLegs()<<" legs and makes the sound: "<<getSound()<<"\n";
}
int getLegs()
{
return legs;
}
string getSound()
{
return sound;
}
};
class Dog: public Animal
{
public:
Dog() : Animal(4,"bark")
{
}
string getClass()
{
return "dog";
}
};
int main()
{
Animal a;
Dog d;
a.printInfo();
d.printInfo();
a=d;
a.printInfo();
return 0;
}
编译和运行结果如下:
这是一个(n)动物。它有 2002819627 条腿并发出声音:
这是一个(n)动物。它有 4 条腿并发出声音:吠声
这是一个(n)动物。它有 4 条腿并发出声音:吠声
为什么当我打电话时我得到“动物”作为班级而不是printInfo()
狗d
?(但仍然以某种方式使腿和声音正确)我Dog
的意思是,为什么getClass
在使用时不起作用printInfo()
;难道我做错了什么?
解决方案
有两点:
- 使用
virtual
方法,getClass
例如Animal()
会返回"Animal",getClass()
例如Dog
会返回"dog"。 - 您使用了默认构造函数
a
,因此legs
包含一些垃圾值,您需要对其进行初始化或删除默认构造函数。
class Animal
{
private:
int legs = DEFAULT_NUMBER_OF_LEGS;
// ^^^^^^^^^^^^^^^^^^^^^^
string sound = "DEFAULT_SOUND";
// ^^^^^^^^^^^^^^^
protected:
Animal(int l, string s) : legs(l), sound(s) {}
public:
Animal() {}
virtual string getClass()
// ^^^^^^^
{
return "Animal";
}
void printInfo()
{
cout <<"This is a(n) "<<getClass()<<". It has "<<getLegs()<<" legs and makes the sound: "<<getSound()<<"\n";
}
int getLegs()
{
return legs;
}
string getSound()
{
return sound;
}
};
class Dog: public Animal
{
public:
Dog() : Animal(4,"bark")
{
}
string getClass() override
// ^^^^^^^^
{
return "dog";
}
};
int main()
{
Animal a;
Dog d;
a.printInfo();
d.printInfo();
a=d;
a.printInfo();
return 0;
}
推荐阅读
- python - 网络机器人中特定方向的旋转
- html - 我的标签在我的下拉菜单中不起作用
- c++ - 重载 operator* 而不分配新内存
- r - 如何在 R 中已经有一些栅格文件的栅格堆栈中添加更多栅格?
- ruby - Ruby 只打印出类方法(而不是继承的方法)
- python - 如何在 Python 中从 JSON 获取有效的正则表达式?
- oracle - 不知道如何(Linux 命令)重新启动 oracle 数据库 12.1.0 服务器
- express - 如何在示例示例中从 ClusterBuster 矢量切片服务器接收切片数据?
- c# - ajax post 不返回视图数据
- sql-server - EF Core 3“更新”SQL 语句