1
多態性を使用して、基本クラスインスタンスから派生した "add
"メソッドを呼び出そうとしています。基本クラスインスタンスから呼び出されたクラスメソッドを呼び出す
しかし、それでも基本クラスRealThing "add
"メソッドを実行します。
私は派生クラスRealThingNextVersion "add
"メソッドを期待していました。 RealThingNextVersion
で
#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'メソッドのバージョンで、2つのパラメータを使って、多態性を通して基本クラスから呼び出せる方法は? – BlueMark
@BlueMark基本クラスに2つのパラメータ 'add'が必要です。 – 1201ProgramAlarm