65,133
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <iostream>
using namespace std;
class CAnimal
{
private:
int isAlive;
public:
CAnimal()
{
cout << "CAnimal constructor" << endl;
}
void breath()
{
cout << "I am CAnimal" << endl;
}
};
class CFish:public CAnimal
{
private:
int inWater;
public:
CFish()
{
cout << "CFish constructor" << endl;
}
void breath()
{
cout << "I am CFish" << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CAnimal *op = NULL;
op->breath();
while (1);
return 0;
}
CAnimal animal1, animal2;
......................
int _tmain(int argc, _TCHAR* argv[])
{
CAnimal *op = NULL;
op->breath(); // NULL 指针解引用,会出现不确定行为,
//这里由于breath没有改动 *this 的任何内容,也没读*this ;
//所以这个函数可以正常工作。
while (1);
return 0;
}
你把CAnimal 写成这样,看看还正常吗?
class CAnimal
{
private:
int isAlive;
public:
CAnimal()
{
cout << "CAnimal constructor" << endl;
}
void breath()
{
cout << "I am CAnimal"<< isAlive<< endl;
}
};
struct Animal {
int isAlive;
};
void Animal_breath(struct Animal* thiz) {
puts("I am Animal");
}
你调用 Animal_breath(NULL); 当然不会有问题。
void breath()
{
cout << "I am CAnimal" << endl;
}
void breath()
{
cout << "I am CAnimal" << isAlive << endl;
}