gpt4 book ai didi

c++ - 继承覆盖

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

我对继承覆盖期间的早期/晚期绑定(bind)有疑问。

因此,我将复习 C++ 的 OOP 基础知识,并阅读如果您不在基类 virtual 上声明函数,则无法覆盖它。但是我有以下代码,看起来我的编译器无论如何都会为我覆盖它。

#include <iostream>

using namespace std;

class Book{
public:
string title;
int number;

Book(){
}

Book(string title){
cout << "book " << title << " created" << endl;
}

void setNumber(int num){
number = num + 7;
}

~Book(){
cout << "book " << title << " destroyed:";
}
};

class Magazine: public Book {
public:

void setNumber(int num){
number = num;
}
};

int main()
{
Magazine mag;
mag.setNumber(4);
cout << mag.title << endl;
cout << "the number you are looking for is: " << mag.number << endl;
}

我的编译器的输出是 4,但是根据我读到的内容,c++ 有早期绑定(bind),如果一个函数没有在基类中声明为 virtual,它就不可能被覆盖,所以它应该输出 num + 7 如基类所述。我只是得到了不正确的资源吗?或者这可能是我的编译器中的错误/异常?

谢谢大家的帮助

最佳答案

您可以“覆盖”非虚函数,但实现将不是动态绑定(bind)而是静态绑定(bind)。你会意识到结合多态性的区别:

Book* mag = new Magazine();
mag->setNumber(4);
cout << mag->title << endl;
cout << "the number you are looking for is: " << mag->number << endl;

这将调用 Book 实现,而当您将成员函数声明为虚拟时,它将动态绑定(bind)到 Magazines 实现。

关于c++ - 继承覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54543282/

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