2015-05-15 31 views
0

我應該爲一個任務創建一個模板類,但是我得到了很多不同的錯誤,我不太明白,有人可以幫我嗎?我附上了我編寫的cp和頭文件。我知道這可能很簡單,但我是新手,謝謝!在Xcode上用C++創建一個模板類

#ifndef __Template_example__Initialisedchecker__ 
#define __Template_example__Initialisedchecker__ 
#include <stdio.h> 
template <class data> 
class Initialisedchecker 
{ 
private: 
    data item; 
    bool definedOrN; 
public: 

    Initialisedchecker() 
    { 
     definedOrN = false; 
    } 

    void setItem(const data&) 
    { 
     std::cin >> item; 
     definedOrN = true; 
    } 


    void displayItem() 
    { 
     if (definedOrN) 
     { 
      std::cout << item; 
     } 
     else 
     { 
      std::cout << "error, your item is undefined"; 
     } 
    } 
}; 
#endif 

這是主要的:

#include <iostream> 
#include "Initialisedchecker.h" 
using namespace std; 
int main() 
{ 
    item <int> x; 
    displayItem(); 
    x = 5; 
    displayItem(); 
} 

對不起,我忘了補充,我發現了錯誤,頭文件不給任何錯誤,但在主要,它說:

Use of undeclared identifier 'display item' , 
Use of undeclared identifier 'item' , 
Use of undeclared identifier 'x' , 
Expected a '(' for function-style cast or type construction 
+1

我看不到錯誤輸出附加 – EdChum

+1

您顯示的錯誤輸出是**不**您的編譯器給您提供的。它永遠不會抱怨包含空格的未聲明的標識符。爲什麼不復制/粘貼實際輸出?如果你期望互聯網上的陌生人花時間幫助你,請花時間做**確切**。 –

回答

2

類模板被稱爲Initialisedchecker,不item。你需要調用對象的成員函數。您需要:

int main() 
{ 
    Initialisedchecker <int> x; 
    x.displayItem(); 
    // this is strange: x = 5; 
    // maybe use: 
    // x.setItem(5); 
    x.displayItem(); 

}