2014-02-05 52 views
2

Main.cpp的「未定義的參考」,而我試圖繼承Vector類

#include <iostream> 
#include "include/Numbers.h" 
#include <vector> 
#include <string> 
#include <fstream> 


using namespace std; 

int main() 
{ 
    ofstream myofile; 
    ifstream myifile; 
    myofile.open("output.txt"); 
    myifile.open("input.txt"); 
    int number; 
    Numbers input; 

    if(myifile.is_open()) 
     while(myifile >> number) { 
      input.push_back(number); 
     } 

    cout << input.size() << endl; 


    myofile.close(); 
    myifile.close(); 

    cout << "Hello world!" << endl; 
    return 0; 
} 

Numbers.h

#ifndef NUMBERS_H 
#define NUMBERS_H 
#include <vector> 


class Numbers: public std::vector<int> 
{ 
    public: 
     Numbers(); 
     ~Numbers(); 
     int size(); 
     Numbers prob(); 

    protected: 
    private: 
}; 

#endif // NUMBERS_H 

Numbers.cpp

#include "../include/Numbers.h" 
#include <iostream> 

using namespace std; 

Numbers::Numbers() 
{ 
} 

Numbers::~Numbers() 
{ 
    //dtor 
} 

I我試圖創建一個新的Numbers類,它繼承了vector類的函數。

我得到的錯誤是未定義的引用'號::大小()雖然功能的push_back沒有給

我使用的代碼塊寫我的代碼的任何問題,我已經包含了所有文件在構建屬性

+0

將'int numbers :: size(){}'添加到Numbers.cpp中 – Borgleader

+0

工作正常。謝謝。但爲什麼沒有給push_back()函數帶來任何問題? – user3276516

+0

因爲你從std :: vector繼承它。您也可以完全刪除尺寸方法,因爲它在那裏定義。 (當我發表第一條評論時,我實際上並沒有注意到你是從矢量繼承的)。 – Borgleader

回答

1

首先,你在做什麼,沒有一個好主意。通常不打算將STL類用作基類(除了專門爲此設計的類,如std :: unary_function)。 std :: vector沒有任何虛方法,所以它沒有作爲公共基類的任何值。使事情變得更糟,性病::矢量甚至沒有虛析構函數,所以當你多態使用它,你可能會創建一個內存泄漏:

void deleteVector(std::vector<int>* v) 
{ 
    delete v; 
} 

deleteVector(new Numbers()); 

在你的情況,你聲明的方法號::大小這在源文件中沒有定義。您可以使用using聲明來使用您的基類的size-method,但這不是公共方法所需的。

class Numbers: private std::vector<int> 
{ 
public: 
    using std::vector<int>::size; 
};