我有一個抽象基類和2個不同的類,它們實現了基類中的虛函數。如果派生類具有私有變量,派生類的數組就不起作用
我把這些放在一個數組中,而對於「derived1」類來說,這是可行的。 但是,如果我創建一個具有一些額外私有變量的「derived2」類的數組,代碼將在運行時進行編譯,但會發生錯誤。
#include <iostream>
class base{
protected:
int inner_a;
int inner_b;
public:
void setInner(int a,int b){inner_a=a;inner_b=b;};
virtual int doStuff()=0;
};
class derived1: public base{
public:
virtual int doStuff();
};
class derived2: public base{
private:
int tmpVar;//works if I remove
public:
int doStuff();
};
int derived2::doStuff(){
return inner_a-inner_b;
}
int derived1::doStuff(){
return inner_a+inner_b;
}
int main(){
base *classAry1 = new derived1[3];//this works
base *classAry2 = new derived2[2];//derived2 has extra private variables
classAry1[0].setInner(1,3);
classAry1[1].setInner(10,7);
std::cout <<classAry1[0].doStuff() <<std::endl;;
std::cout <<classAry1[1].doStuff() <<std::endl;
classAry2[0].setInner(1,3);
classAry2[1].setInner(10,7);
std::cout <<classAry2[0].doStuff() <<std::endl;;
std::cout <<classAry2[1].doStuff() <<std::endl;
return 0;
}
任何人都可以幫助我,關於如何把派生類放在一個std數組?
感謝
編輯:
的代碼段錯誤,並Valgrind的告訴我
-2
==25096== Use of uninitialised value of size 8
==25096== at 0x400AC9: main (abc.cpp:52)
==25096==
==25096== Invalid read of size 8
==25096== at 0x400AC9: main (abc.cpp:52)
==25096== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==25096==
==25096==
==25096== Process terminating with default action of signal 11 (SIGSEGV)
==25096== Access not within mapped region at address 0x0
==25096== at 0x400AC9: main (abc.cpp:52)
什麼是「錯誤在運行時」是什麼意思? 「不起作用」是什麼意思? – AnT 2011-06-07 23:23:25