2013-05-09 99 views
5

我正在處理C++中的繼承問題。我想寫一個程序來加減兩個數組。我的繼承人代碼:對'typeinfo for class'的未定義引用以及對'class'的vtable的未定義引用

#include <iostream> 
#include <cmath> 
#include <sstream> 
using namespace std; 

class root 
{ 
    protected : 

      int size; 
      double *array; 

    public : 

     virtual ~root() {} 
     virtual root* add(const root&) = 0; 
     virtual root* sub(const root&) = 0; 
     virtual istream& in(istream&, root&) = 0; 

     virtual int getSize() const = 0; 
     virtual void setSize(int); 
     virtual int getAt(int) const = 0; 
}; 

class aa: public root 
{ 

    public : 

     aa(); 
     aa(int); 
     aa(const aa&); 
     root* add(const root& a); 
     root* sub(const root& a); 
     istream& in(istream&, root&){} 
     int getSize() const; 
     void setSize(int); 
     int getAt(int) const; 
}; 

class bb: public root 
{ 
public: 
    bb() { } 
    bb(const bb& b) { } 
    root* add(const root& a); 
    root* sub(const root& a); 
    istream& in(istream&, root&){} 
    int getSize() const{} 
    void setSize(int){} 
    int getAt(int) const{} 
}; 

aa::aa() 
{ 
    size = 0; 
    array = NULL; 
} 

aa::aa(int nsize) 
{ 
    size = nsize; 
    array = new double[size+1]; 
    for(int i=0; i<size; i++) 
     array[i] = 0; 
} 

root* aa::add(const root& a) 
{ 
    for (int i=0; i<a.getSize(); i++) 
     array[i] += a.getAt(i); 
    return new aa(); 
} 

root* aa::sub(const root& a) 
{ 
} 

int aa::getSize() const 
{ 
    return size; 
} 

void aa::setSize(int nsize) 
{ 
    size = nsize; 
    array = new double[size+1]; 
    for(int i=0; i<size; i++) 
     array[i] = 0; 
} 

int aa::getAt(int index) const 
{ 
    return array[index]; 
} 

root* bb::add(const root& a) 
{ 
    return new bb(); 
} 

root* bb::sub(const root& a) 
{ 

} 

int main(int argc, char **argv) 
{ 
} 

但我有一個奇怪的錯誤:

/home/brian/Desktop/Temp/Untitled2.o||In function `root::~root()':| 
Untitled2.cpp:(.text._ZN4rootD2Ev[_ZN4rootD5Ev]+0xb)||undefined reference to `vtable for root'| 
/home/brian/Desktop/Temp/Untitled2.o||In function `root::root()':| 
Untitled2.cpp:(.text._ZN4rootC2Ev[_ZN4rootC5Ev]+0x8)||undefined reference to `vtable for root'| 
/home/brian/Desktop/Temp/Untitled2.o:(.rodata._ZTI2bb[typeinfo for bb]+0x8)||undefined reference to `typeinfo for root'| 
/home/brian/Desktop/Temp/Untitled2.o:(.rodata._ZTI2aa[typeinfo for aa]+0x8)||undefined reference to `typeinfo for root'| 
||=== Build finished: 4 errors, 0 warnings ===| 

不知道從他們來自哪裏,現在不如何「修復」它們。在此先感謝;)

+1

請勿使用裸指針。只是不要去那裏。這是非常糟糕的代碼。 (另外,查看構造函數初始化列表的工作方式。) – 2013-05-09 11:23:19

回答

12

root::setSize未聲明純虛擬的,這意味着它必須定義爲純虛函數。據推測,它應該是純的其他功能:

virtual void setSize(int) = 0; 
          ^^^ 

如果你感興趣的,爲什麼你得到的特定錯誤的血淋淋的細節:這個編譯器需要的地方生成類的虛擬/ RTTI元和,如果類聲明瞭非純的非內聯虛函數,它將在與該函數的定義相同的翻譯單元中生成它。由於沒有定義,它們不會被生成,從而產生錯誤。

+1

+1給予血淋淋的細節! – Nick 2013-05-09 11:36:08

1

您的root::setSize未定義,且未聲明爲純虛函數。將= 0添加到該函數的末尾(使其成爲純粹的虛擬),或者定義一個root::setSize函數。

1

我相信那是因爲你還沒有root實施

virtual void setSize(int); 

或宣佈其加入=0

相關問題