gpt4 book ai didi

c++ - 从基类实例调用派生类方法

转载 作者:行者123 更新时间:2023-11-30 03:43:25 27 4
gpt4 key购买 nike

我正在尝试使用多态性,从基类实例调用派生的“add”方法。

但它仍然想要运行基类 RealThing“add”方法。

我期待派生类 RealThingNextVersion“add”方法。

#include <iostream>
#include <string>
using namespace std;

class VirtualObject
{
public:
virtual void load() {
cout << "Nothing to load." << endl;
}

void import(string file) {
//here some importing stuff
}
};

class RealThing :public VirtualObject
{
private:
string file;

protected:
int id;

public:
RealThing(string fileName = "data.txt") { file = fileName; }

void load() {
this->import(this->file);
cout << "Thing data loaded." << endl;
}

virtual void add(int id) {
cout << "Added V1: " << id << endl;
};
};

class RealThingNextVersion : public RealThing
{
public:
string desc;

public:
virtual void add(int id, string desc) {
cout << "Added V2: " << id << " with description " << desc << endl;
};
};


int main() {
RealThing rt;
RealThingNextVersion rtv;

RealThing* r;
r = &rt;
r->load(); // OK., returns: Thing data loaded.
r->add(11); // OK., returns: Added V1: ...

r = &rtv;
r->add(22, "info"); // Here "Error: too many arguments in function call"
// it still want's to run RealThing "add",
// and I was expecting RealThingNextVersion "add"


system("pause");
}

最佳答案

RealThingNextVersion 中的addRealThing 中的调用签名不同(不同的参数),因此它是一个不同的函数并且不是 add 的重写。如果在函数声明中添加 override 关键字

virtual void add(int id, string desc) override;

使用最新的编译器,编译器会告诉您您没有覆盖任何内容。

关于c++ - 从基类实例调用派生类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109649/

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