gpt4 book ai didi

c++ - 无法理解 C++ `virtual`

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:19 24 4
gpt4 key购买 nike

我无法理解 C++ 中 virtual 关键字的用途。我非常了解 C 和 Java,但我是 C++ 的新手

来自维基百科

In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature.

不过,我可以在不使用 virtual 关键字的情况下覆盖如下所示的方法

#include <iostream>

using namespace std;

class A {
public:
int a();
};

int A::a() {
return 1;
}

class B : A {
public:
int a();
};

int B::a() {
return 2;
}

int main() {
B b;
cout << b.a() << endl;
return 0;
}

//output: 2

正如你在下面看到的,函数 A::a 被 B::a 成功覆盖,而不需要 virtual

让我感到困惑的是关于虚拟析构函数的声明,也来自维基百科

as illustrated in the following example, it is important for a C++ base class to have a virtual destructor to ensure that the destructor from the most derived class will always be called.

所以 virtual 还告诉编译器调用父级的析构函数?这似乎与我最初将virtual理解为“使函数可覆盖”

大相径庭

最佳答案

进行以下更改,您将了解原因:

#include <iostream>

using namespace std;

class A {
public:
int a();
};

int A::a() {
return 1;
}

class B : public A { // Notice public added here
public:
int a();
};

int B::a() {
return 2;
}

int main() {
A* b = new B(); // Notice we are using a base class pointer here
cout << b->a() << endl; // This will print 1 instead of 2
delete b; // Added delete to free b
return 0;
}

现在,让它像您预期的那样工作:

#include <iostream>

using namespace std;

class A {
public:
virtual int a(); // Notice virtual added here
};

int A::a() {
return 1;
}

class B : public A { // Notice public added here
public:
virtual int a(); // Notice virtual added here, but not necessary in C++
};

int B::a() {
return 2;
}

int main() {
A* b = new B(); // Notice we are using a base class pointer here
cout << b->a() << endl; // This will print 2 as intended
delete b; // Added delete to free b
return 0;
}

您包含的关于虚拟析构函数的注释是完全正确的。在您的示例中,没有任何需要清理的东西,但是说 A 和 B 都有析构函数。如果它们没有标记为虚拟,那么将使用基类指针调用哪个?提示:它的工作方式与未标记为虚拟时的 a() 方法完全相同。

关于c++ - 无法理解 C++ `virtual`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1829013/

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