与其进行冗长的解释,我认为几行代码会更清楚地解释我的问题。假设我有 2 个类,一个继承自另一个:
#include <iostream>
class A{
public:
void parse()
{
treatLine();
};
void treatLine()
{
std::cout << "treatLine in A" << std::endl;
}
};
class B : public A{
public:
void treatLine()
{
std::cout << "treatLine in B" << std::endl;
}
};
int main()
{
B b;
b.parse();
return 0;
}
执行时,令我惊讶的是,它会打印“treatLine in A”。是否可以使用 B 类型的对象调用 B 类中的函数 TreatLine(即上面的代码将打印“B 中的treatLine”)?并保留创建 A 类型对象的可能性,该对象将打印“treatLine in A”