C++ 纯虚类的奇怪行为
请帮助该死的 C++ 初学者更好地理解纯虚类。
我尝试了一个使用 C++ 虚拟机的简单示例,但不确定结果。 如果我在另一种编程语言中尝试与 java 相同,例如输出将是
期望/预期输出
1 -> Tweet
2 -> Tweet
然而,这里的输出是
实际输出
1 -> Meow
2 -> Tweet
这是为什么呢? 动物类的 operator= 似乎没有效果。 那是因为调用了动物类的标准 operator= 什么都不做吗? 如何在不使用指针的情况下实现类似于 java 的行为? 这可能吗?
下面是一个尽可能简化的代码示例:
代码
#include <string>
#include <iostream>
using namespace std;
class Animal
{
public:
virtual string test() const = 0;
};
class Cat : public Animal
{
public:
virtual string test() const
{
return "Meow";
}
};
class Bird : public Animal
{
public:
virtual string test() const
{
return "Tweet";
}
};
void test_method(Animal &a)
{
Bird b;
a = b;
cout << "1 -> " << a.test() << endl;
cout << "2 -> " << b.test() << endl;
}
int main(int args, char** argv)
{
Cat c;
Animal &a = c;
test_method(a);
return 0;
}
最佳答案
显然,您对 a = b
赋值的行为有一些不切实际的期望。
您的a = b
赋值只是将Bird
对象b
的Animal
子对象的数据复制到
子对象。由于 a
引用的 Cat
对象的 AnimalAnimal
中根本没有数据,因此 a = b
是一个空操作,一个空操作。它根本不做任何事情。
但即使它做了一些事情,它也只会复制数据字段。它不能复制对象的多态标识。在 C++ 中无法更改对象的多态标识。无法更改对象的类型。无论您做什么,Cat
始终是 Cat
。
你写的代码可以缩短为
Cat a;
Bird b;
(Animal &) a = b; // Same as `(Animal &) a = (Animal &) b`
a.test(); // still a `Cat`
b.test(); // still a `Bird`
你以更模糊的方式做了同样的事情。
关于c++ - 奇怪的行为 C++ 纯虚拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21539045/