#include <iostream>
using namespace std;
class animal
{
public:
void breathe()
{
cout << "breathe!" << endl;
}
int height;
};
class fish : public animal
{
public:
void breathe()
{
cout << "fish breathe!" << endl;
}
int weight;
};
int main()
{
animal *p_animal = new animal();
fish *p_fish = (fish *)p_animal;
p_fish->breathe();
p_fish->weight = 2;
cout << p_fish->weight; //I new a animal instance,but why does it has weight property?
int temp;
cin >> temp;
}
答案 0 :(得分:1)
正如各种评论者所指出的那样,你可以欺骗编译器让你这样做。
关键是
fish *p_fish = (fish *)p_animal;
这一行基本上迫使编译器接受 p_animal指向的,它现在指向一条鱼。
如果您能够访问那里的属性,那么它基本上是偶然的,并且不同的编译器可能会给您不同的结果。
如果你写过
fish *p_fish = p_animal;
然后编译器会抱怨。
答案 1 :(得分:0)
对您的代码提出一些意见。
在此示例中,您可能需要虚拟功能。请参阅以下修改代码:
#include <iostream>
class Animal
{
public:
virtual ~Animal() {} // Always define virtual destructor in this case
virtual void breathe() const // This fonction doesn't modify the object
{ // then, add 'const' at the end
std::cout << "breathe!" << std::endl;
}
unsigned int height; // An animal can't have a negative height ;-)
// then, use an unsigned type.
};
class Fish : public Animal
{
public:
virtual ~Fish() {}
virtual void breathe() const
{
std::cout << "fish breathe!" << std::endl;
}
unsigned int weight;
};
int main()
{
Animal* p_animal = new Animal; // Don't put () for empty constructor
Animal* p_fish = new Fish;
p_animal->breathe(); // this prints "breathe!"
p_fish->breathe(); // this prints "fish breathe!" even if the pointer is
// an pointer to Animal. It's the behaviour of virtual
// functions : when the code is executed, the real type
// is checked and the corresponding function is called.
p_fish->height = 10; // This works
// p_fish->weight = 5; // This doesn't compile, it's an pointer to Animal
Fish* p_real_fish = dynamic_cast<Fish*>(p_fish);
p_real_fish->height = 10; // This works
p_real_fish->weight = 5; // This works too
delete p_animal; // Don't forget to release the memory !
delete p_fish;
}
我希望这可以帮到你。