[英]converting base class pointer to unknown derived class pointer
I have 5 derived classes from an abstract base class. 我有一个抽象基类的5个派生类。 One function is overloaded which exists in every derived class , let's name it,
print()
. 每个派生类中都存在一个重载的函数 ,我们将其命名为
print()
。 Example for Derived 4 class: 派生4类的示例:
Derived4::print(*Derived1)
Derived4::print(*Derived2)
Derived4::print(*Derived3)
Derived4::print(*Base)
Like i said before, all derived classes have print function, but arguments are different, like 就像我之前说过的,所有派生类都具有打印功能,但参数却不同,例如
Derived1::print(*Derived2)
Derived1::print(*Derived3)
Derived1::print(*Derived4)
Derived1::print(*Base)
All objects are stored inside a vector like 所有对象都存储在像
vector<Base*> a
When i take one of them from vector and try to call print function, all calls are directed to print(*Base) function.I am not allowed to store the types, therefore don't have any idea what is coming from vector.Also, type checking is not allowed too. 当我从vector中提取其中之一并尝试调用print函数时,所有调用都定向到print(* Base)函数。我不允许存储类型,因此不知道vector来自什么。 ,也不允许类型检查。
An example: 一个例子:
#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;
}
The result: 结果:
greetings from A
greetings from A
The desired result: 预期结果:
greetings from C
greetings from A
You need virtual functions. 您需要虚拟功能。 declaring
A::print
as virtual would make it so that calling print on a pointer of type A
will call the print
of which class the object was constructed as, instead of using pointer type to decide what print
to call. A::print
声明为虚拟将使之成为事实,以便在类型为A
的指针上调用print会调用构造对象的类的print
,而不是使用指针类型来决定要调用的print
。
You also need to remove D::print
as you expect A::print
get called if the object is of type D
您还需要删除
D::print
,如果对象为D
类型,则会调用A::print
。
#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;
}
The result: 结果:
This is desired output.
This is printed twice.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.