从基类实例调用派生类方法
Call derived class method from base class instance
我正在尝试使用多态性,从基类实例调用派生的"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
中的 add
与 RealThing
中的调用签名(不同的参数)不同,因此它是一个不同的函数,而不是 add
的覆盖。 如果在函数声明中添加 override
关键字
virtual void add(int id, string desc) override;
使用最近的编译器,编译器会告诉您您没有覆盖任何内容。
相关文章:
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 从基类实例调用派生类方法而不进行强制转换
- C++ 使用派生类方法更改基类数据成员
- 将派生类方法与基类unique_ptr一起使用
- 使用派生类C++方法的超类
- 从库类扩展,然后如何让库调用派生类方法
- 当应该调用派生类方法时,为什么要调用基类方法
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++
- 如何轻松地将 Base 方法重定向到相同的派生类方法
- Gmock Base类方法中的派生类方法
- 如何调用精确派生类方法?
- 为什么可以从实例化基类对象的投射指针调用非静态派生类方法
- C++使用基类指针访问派生类方法
- 调用派生类方法时出现分段错误
- 从基类析构函数调用派生类方法
- 基类的指针数组:如何调用唯一的派生类方法
- 派生类方法的默认参数的最佳实践
- 从基类实例调用派生类方法
- C++ 继承:指向基类的派生类指针调用派生类方法
- 虚函数未解析为大多数派生类方法