gpt4 book ai didi

c++ - 非虚重载成员函数

转载 作者:行者123 更新时间:2023-11-27 23:57:26 26 4
gpt4 key购买 nike

这段代码

#include <iostream>

struct A {
int one() {
std::cout << "oneA" << std::endl;
}
int devone() {
one();
}
};

struct B : A {
int one() {
std::cout << "oneB" << std::endl;
}
};
int main() {
B b;
b.devone();
}

打印oneA

我不明白为什么。我知道如果我使用虚函数 oneB 会被打印出来,但为什么在上面的代码示例中没有。没有使用指针或引用,为什么我需要将函数声明为虚函数?

最佳答案

No pointers or references are used, why do I need to declare the function virtual?

你错了,这段代码:

 int A::devone() {
one();
}

等于:

int A::devone() {
this->one();
}

因此使用了指针,并且要在运行时解析正确的函数,您必须使用 virtual 函数。

关于c++ - 非虚重载成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41615686/

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