我正在尝试使用多态,来调用派生的" 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");
}
答案 0 :(得分:2)
add
中的RealThingNextVersion
与RealThing
中的add
具有不同的呼叫签名(不同的参数),因此它是一个不同的功能,而不是override
的覆盖。如果在函数声明中添加virtual void add(int id, string desc) override;
关键字
DataGridViewRow row = (DataGridViewRow)nameOfYourGrid.Rows[0].Clone();
row.Cells[0].Value = "Dr";
row.Cells[1].Value = "Ledger 1";
row.Cells[2].Value = 500.0;
row.Cells[3].Value = 0.0;
yourDataGridView.Rows.Add(row);
使用最近的编译器,编译器会告诉您,您没有覆盖任何内容。