gpt4 book ai didi

c++ - 继承和重载函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:59 25 4
gpt4 key购买 nike

与其解释很长,我认为几行代码会更清楚地解释我的问题。假设我有 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;
}

执行时,令我惊讶的是,它会打印“A 中的 treatLine”。是否有可能使 B 类中的函数 treatLine 被 B 类型的对象调用(即上面的代码将打印“B 中的 treatLine”)?并保留创建 A 类型对象的可能性,该对象将打印“A 中的 treatLine”

最佳答案

treatLine 虚拟化:

virtual void treatLine() {
std::cout << "treatLine in A" << std::endl;
}

这样,函数将根据对象的运行时类型(称为“动态类型”)而不是编译时类型(称为对象的“静态类型”)。

关于c++ - 继承和重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com