我有一个来自抽象基类的5个派生类。 一个功能会重载,在每个派生类中都存在,我们将其命名为print()
。派生4类的示例:
Derived4::print(*Derived1)
Derived4::print(*Derived2)
Derived4::print(*Derived3)
Derived4::print(*Base)
就像我之前说过的,所有派生类都有print函数,但参数不同,比如
Derived1::print(*Derived2)
Derived1::print(*Derived3)
Derived1::print(*Derived4)
Derived1::print(*Base)
所有对象都存储在像
这样的矢量中vector<Base*> a
当我从vector中取出其中一个并尝试调用print函数时,所有调用都指向print(* Base)函数。我不允许存储类型,因此不知道是什么来自vector.Also,也不允许进行类型检查。
一个例子:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
void print(){cout << "greetings from A" << endl;}
};
class C : public A{
public:
void print(){cout << "greetings from C" << endl;}
};
class D : public A{
public:
void print(){cout << "greetings from D" << endl;}
};
class B : public A{
public:
void print(C* c){c->print();}
void print(A* d){d->print();}
};
int main()
{
D d;
C c;
B b;
vector<A*> a; //B,C,D will be stored inside a vector like this.
a.push_back(&c);
a.push_back(&d);
b.print(a[0]);
b.print(a[1]);
return 0;
}
结果:
greetings from A
greetings from A
期望的结果:
greetings from C
greetings from A
答案 0 :(得分:1)
您需要虚拟功能。声明A::print
为虚拟会使得在A
类型的指针上调用print将调用构造对象的类的print
,而不是使用指针类型来决定什么print
致电。
如果对象的类型为D::print
A::print
,因为您希望D
被调用
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
virtual void print(){ cout << "This is printed twice." << endl; }
};
class C : public A{
public:
void print(){ cout << "This is desired output." << endl; }
};
class D : public A{
};
class B : public A{
public:
void print(C* c){ c->print(); }
void print(A* d){ d->print(); }
};
int main()
{
D d;
C c;
B b;
vector<A*> a; //B,C,D will be stored inside a vector like this.
a.push_back(&c);
a.push_back(&d);
b.print(a[0]);
b.print(a[1]);
return 0;
}
结果:
This is desired output.
This is printed twice.