本文介绍了poliporphism的一个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 您好。我会尝试用一个例子来解释我的问题: 我有以下课程: A级{ public: 字符串名称; .... }; class B:public A { B(int x){b = x; name ="我是B" ;; } int b; getB(){return b}; }; C级:公共A { C(int x){c = x; name ="我是C" ;; } int c; getC(){return c; } }; 现在,我需要一个向量< A *> v; 有如下函数: void p() { ... 如果(v [i] - > name =="我是B"){v [i] - > getB()... }; ... if(v [j] - > name ==" I am C"){v [j] - > getC( )...}; ... }; 它不起作用,因为v包含A类,但A不是实现getB()也不是getC()。 但我需要在A,B和C的相同向量对象中而且我不希望 在A中将getB和getC声明为虚拟,因为这些方法只会分别在B和C类中定义。\\ br 。 /> 我该怎么做? 谢谢。 解决方案 public: C(int x){c = x; name ="我是C" ;; } getC(){return c; } int getC(){return c; } 声明 virtual int getValue()= 0; 并使B和C分别通过调用getB和getC来实现它。 V 如果C是这样的(A和B就像之前): C级{ int c1,c2; public: int getC1(){return c1; } int getC2(){return c2; } }; vector< A *> v; void p() { .... v [i] - > getC1 (); ... v [i] - > getC2(); ... } 另一个问题: list< A *> l; A * p =新C(...); l.push_front(p); l.pop_front() ; 被* p销毁? 甚至更多:将列出< A *>'的析构函数销毁所有元素l? Hello. I''ll try to explain my problem with an example: I have the following classes: class A {public:string name;....}; class B : public A{B(int x) {b=x; name="I am B"; }int b;getB() { return b };}; class C : public A{C(int x) {c=x; name="I am C"; }int c;getC() { return c; }}; Now, I need a vector<A*> v; An there is a function like the following: void p(){...if(v[i]->name=="I am B"){ v[i]->getB() ...};...if(v[j]->name=="I am C") { v[j]->getC() ... };...}; It doesn''t work because v contains objects of class A, but A doesn''timplement getB() nor getC().But I need to have in the same vector objets of A, B and C. And I don''t wantto declare getB and getC as virtual in A, because these methods will only bedefined in classes B and C respectively. How can I do that? Thanks. 解决方案 public: C(int x) {c=x; name="I am C"; } getC() { return c; } int getC() { return c; } Declare virtual int getValue() = 0; in A and make B and C implement it by calling getB and getC respectively. V what about if C is like this (A and B are like before): class C {int c1, c2;public:int getC1() { return c1; }int getC2() { return c2; }}; vector<A*> v;void p(){....v[i]->getC1();...v[i]->getC2();...} And another question: list<A*> l;A* p = new C(...);l.push_front(p);l.pop_front(); is *p destroyed? Or even more: will list<A*>''s destructor destroy all the elements of l ? 这篇关于poliporphism的一个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-03 14:07