【发布时间】:2019-06-29 19:05:46
【问题描述】:
我有一个关于继承覆盖期间的早期/晚期绑定的问题。
因此,我将介绍 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++ 具有早期绑定,如果函数未在基类中声明为虚拟,则不应覆盖它,因此应输出 num + 7 如基类所述。我只是得到了不正确的资源吗?或者这可能是我的编译器中的错误/异常?
感谢大家的帮助
【问题讨论】: