2016-10-01 31 views
0

我的函數原型如下所示:非成員函數 '廉政找到(常量T&)' 不能具有CV-預選賽

// Purpose: finds an element in the ArrayList 

// Parameters: 'x' is value to be found in the ArrayList 

// Returns: the position of the first occurrance of 'x' in the list, or -1 if 'x' is not found. 

int find(const T& x) const; 

它被放置在類的ArrayList

template <typename T> 
class ArrayList 
{ 
    private: 
    int m_size;       // current number of elements 
    int m_max;       // maximum capacity of array m_data 
    T* m_data;       // array to store the elements 

    T m_errobj;       // dummy object to return in case of error 


    public: 
    int find(const T& x) const; 

我的定義是:

template <typename T> 
int find(const T& x) const 
{ 
    int i; 
    while (m_data[i]!=x && m_data[i]!=NULL) 
    i++; 
    if (m_data[i]=x) 
    return i; 
    else 
return (-1); 
} 

每當我編譯時,我收到標題中的錯誤,並沒有在範圍內聲明m_data的錯誤。我該如何解決?

編輯:我改變了定義

int ArrayList<T>:: find(const T& x) const 

我有一噸的錯誤

int ArrayList:: find(const T& x) const 

沒工作,要麼

+0

不應該它在課堂內嗎? – immibis

+0

嗯......聽起來就像你正在類範圍之外定義類成員函數一樣。你必須使用像ArrayList :: find(....)const'這樣的類名來限定它。另外,你應該知道你不能真的* [split template](http:// stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)header/implementation。 – WhiZTiM

+0

我的函數原型是在一個類ArrayList裏面 – cjackson

回答

1

模板必須在頭文件中定義。在你的情況下,你將它分成.h/.cpp。爲了工作,您需要將其與您的類定義一起定義。事情是這樣的:

template <typename T> 
class ArrayList 
{ 
private: 
    int m_size;       // current number of elements 
    int m_max;       // maximum capacity of array m_data 
    T* m_data;       // array to store the elements 

    T m_errobj;       // dummy object to return in case of error 

public: 
    int find(const T& x) const; 
}; 

#include "x.hpp" 

,並在文件中x.hpp定義它

template <typename T> 
int ArrayList<T>::find(const T& x) const 
{ 
    int i; 
    while (m_data[i]!=x && m_data[i]!=NULL) 
    i++; 
    if (m_data[i]=x) 
     return i; 
    else 
     return (-1); 
} 

注意,這有相同的效果,你已經在一個獨特的頭文件中定義的一切

+0

這給了我很多錯誤 – cjackson

+1

這不會給我任何錯誤。你得到了什麼錯誤?當然,如果你嘗試使用它,你會遇到各種各樣的問題,但這是另一個問題。 –

相關問題