2011-10-04 101 views
-2

顯然的push_back()不工作我的自定義數據類T.在編譯時,我得到以下錯誤:的push_back()不工作的自定義數據類型(模板類)

error: no matching function for call to ‘Vector::push_back(int&)’

有人能向我解釋爲什麼是這樣?謝謝。

#include <std_lib_facilities> 
#include <numeric> 
#include <vector> 
#include <string> 

// vector<int> userin;                                               
// int total;                                                  
// bool success;                                                 

class T 
{ 
public: 
    void computeSum(vector<T> userin, int sumamount, T& total, bool& success); 
    void getData(vector<T> userin); 
}; 

template <class T> 
void computeSum(vector<T> userin, int sumamount, T& total, bool& success) 
{ 

    if (sumamount < userin.size()){ 
     success = true; 
     int i = 0; 
     while (i<sumamount){ 
      total = total + userin[i]; 
      ++i; 
     } 
    } else { 
     success = false; 
     cerr << "You can not request to sum up more numbers than there are.\n"; 
    } 

} 

template <class> 
void getData(vector<T> userin) 
{ 
    cout << "Please insert the data:\n"; 
    int n; 

    do{ 
     cin >> n; 
     userin.push_back(n); 
    } while (n); 

    cout << "This vector has " << userin.size() << " numbers.\n"; 
} 

int helper() 
{ 
    cout << "Do you want help? "; 
    string help; 
    cin >> help; 
    if (help == "n" || help == "no"){ 
     return 0; 
    }else{ 
     cout << "Enter your data. Negative numbers will be added as 0. Ctrl-D to finish inputing values.\n"; 
    } 
} 

int main() 
{ 
    helper(); 
    getData(userin); 

    cout << "How many numbers would you like to sum?"; 
    int sumamount; 
    cin >> sumamount; 
    computeSum(userin, sumamount); 
    if (success = true) { 
     cout << "The sum is " << total << endl; 
    } else { 
     cerr << "Oops, an error has occured.\n"; 
    } 

    cout << endl; 
    return 0; 
} 
+0

您提供的代碼有更嚴重的錯誤 - 沒有'computeSum'函數取兩個參數,例如,'template '是錯誤的。這真的是你得到的唯一錯誤嗎?請提供您真正使用的代碼 - 不要重新輸入錯誤,複製並粘貼它們。此代碼中沒有大寫的Vector類。 – bdonlan

+0

嘿,我已經跟在這裏:http://stackoverflow.com/questions/7657825/c-error-calling-template-functions –

回答

2

以外的一些悍然進攻的問題(例如,它應該是template <class T>,不template<class>),真正的問題是,矢量希望你推回T類型的對象。它看起來像你正在閱讀類型int和推。嘗試:

template <class> 
void getData(vector<T> userin) 
{ 
    cout << "Please insert the data:\n"; 
    T n; 

    do{ 
     cin >> n; 
     userin.push_back(n); 
    } while (n); 

    cout << "This vector has " << userin.size() << " numbers.\n"; 
} 
0

的問題是這一行:

userin.push_back(n); 

其中n是一個int。 push_back期待T類型的東西。

我也不確定類T的點在這種情況下。