【发布时间】:2015-04-22 20:00:59
【问题描述】:
请检查下面的代码:
class Human
{
public:
void chat(Human h)
{
cout << "human";
}
void chat(ComputerScientist c)
{
cout << "computer";
}
};
class ComputerScientist : public Human
{
};
//Main function below
int main()
{
Human* p, p1;
//Uninitialized pointer above;
p->chat(p1); //It shows perfectly the result without ANY error!
}
但是,如果我在派生类 ComputerScientist 中创建一个覆盖人类函数的函数,事情就会变得棘手。
class Human
{
public:
virtual void chat(Human* h)
{
cout << "about the weather";
}
virtual void chat(ComputerScientist* c)
{
cout << "about their own computer illiteracy";
}
};
class ComputerScientist : public Human
{
public:
virtual void chat(Human* h)
{
cout << " about computer games";
}
virtual void chat(ComputerScientist* c)
{
cout << " about others’ computer illiteracy";
}
};
而且我使用相同的 main 函数,它似乎是空指针行中的分段错误。但为什么呢?
第二个例子中的两个地方发生了变化:
- 我通过将其设为虚拟来使用覆盖函数。
- 函数将指针作为参数。
【问题讨论】:
-
“C 让你很容易射中自己的脚;C++ 让它更难,但是当你这样做时,它会炸掉你的整条腿。” --- 某人
-
还要注意在
human* p, p1;中只有p是一个指针。如果您希望两者都是指针,请使用human *p, *p1; -
“C 语言让你很容易在脚下开枪”引用stroustrup.com/bs_faq.html#really-say-that。
标签: c++ oop computer-architecture