2014-04-29 57 views
0

我不知道如何處理班級內的結構。我認爲我的第一部分是正確的,但沒有任何主要工作。當我嘗試運行我的程序它說:「函數不接受0參數」我應該寫一切都在主是這樣的:私人結構

P.Read(BOX m); 

這裏是我到目前爲止的代碼如下:

#include <iostream> 
#include <string> 
using namespace std; 
template <class T, int n> 
class SIX 
{ 
private: 
    struct BOX 
    { 
     T a[n]; 
     string name; 
    }; 
public: 
    void Read(BOX m) 
    { 
     cout<<"Enter your name: "; 
     cin>>m.name; 
     cout<<m.name<<" please enter "<<n<<" data: "; 
     for(int i=0;i<n;++i) 
      cin>>m.a[i]; 
    } 
    void SortArray(BOX m) 
    { 
     sort(m.a, m.a+n); 
    } 
    void Display(BOX m) 
    { 
     cout<<m.name<<" this is the sorted list of data in your array a: "; 
     for(int i=0;i<n;++i) 
      cout<<m.a[i]<<'\t'; 
     cout<<endl; 
    } 
}; 
int main() 
{ 
    SIX <int, 6> P; 
    SIX <string, 5> Q; 

    P.Read(); 
    P.SortArray(); 
    P.Display(); 
    cout<<endl; 

    Q.Read(); 
    Q.SortArray(); 
    Q.Display(); 
    cout<<endl; 

    system("pause"); 
    return 0; 
} 

回答

0

沒有,定義Read

void Read() 
{ 
    cout<<"Enter your name: "; 
    cin>>BOX.name; 
    cout<<BOX.name<<" please enter "<<n<<" data: "; 
    for(int i=0;i<n;++i) 
     cin>>BOX.a[i]; 
} 

Read是一個成員函數,並且它可以訪問Box,所以這是你必須做的。 與其他功能相同,您不需要指定BOX m作爲參數,將其替換爲(),並在代碼內將m替換爲BOX

正如@Barmar指出的,您的struct BOX只是定義了一個類型,您應該定義一個名爲BOX的成員變量。做到這一點最簡單的方法是正義之舉BOXstruct聲明的末尾,

struct 
{ 
    T a[n]; 
    string name; 
} BOX; 
+0

'BOX'不是一個變量,它是一個結構類型。 – Barmar

+0

哦,是的,你說得對,但他應該把它變成一個成員變量。我讀得很快,首先想到他定義了這個變量,因爲他實際上並沒有在課堂外使用這個類型。 – vsoftco

+0

這是我所得到的,當我嘗試運行它在編譯類模板成員函數 'void SIX :: SortArray(無效)' 有沒有發現 「排序」 標識 [ T = INT, N = 6 ] – user3326689