2014-09-03 100 views
-2

我無法打印頭文件中的內容。當我把所有的代碼放在一個cpp文件中時,一切都正常,但是當我嘗試使用頭文件時,它不會運行。在頭文件中使用結構C++

這是我的頭文件,vet.h

#ifndef Vet 
#define Vet 

class LIST 
{ 
private: 
    struct PET 
    { 
     string last_name; 
     string pet; 
     string animal; 
     string color; 
     int dob; 
}; 
//enter data 
public: 
void Read 
{ 
    cout<<"Your pets first name: "; 
    cin>>PET.pet; 
    cin.ignore(); 
    cout<<"Your last name: "; 
    cin>>PET.last_name; 
    cin.ignore(); 
    cout<<"What kind of animal do you have: "; 
    cin>>PET.animal; 
    cin.ignore(); 
    cout<<"Your animals dob: "; 
    cin>>PET.dob; 
    cin.ignore(); 
    cout<<"Your animals color: "; 
    cin>>PET.color; 
    cin.ignore(); 
} 
}; 
#endif 

,這是我的cpp文件,Veterinary.cpp

//read from header file 
#include <iostream> 
#include <string> 
#include <stdio.h> 
#include <algorithm> 
#include "Vet.h" 
using namespace std; 
int main() 
{ 
LIST P; 

P.Read(); 

system("pause"); 
return 0; 
} 
+4

'無效Read' - >'無效閱讀()' – 2014-09-03 19:37:43

+4

和'#包括 ...'+'的std ::'在頭.. – quantdev 2014-09-03 19:38:21

+5

' PET'是一個類型的名稱,而不是一個變量。您需要一個實際的'PET'結構,然後才能設置其字段。 – 2014-09-03 19:39:07

回答

0

類有型PET的任何數據成員,從而成員函數讀是無效的。您需要定義一個類型爲PET的數據成員,並在其中輸入關於寵物的數據。 C++沒有匿名結構。

還要考慮到使用名稱空間標準指令的指令必須放在此類標頭的類定義之前。此外,如果您將頭文件<iostream><string>包含在頭文件中,並使用合格的標準名稱而不是使用僞指令會更好。

頭可能看起來像

#ifndef Vet 
#define Vet 

#include <iostream> 
#include <string> 

class LIST 
{ 
private: 
    struct PET 
    { 
     std::string last_name; 
     std::string pet; 
     std::string animal; 
     std::string color; 
     int dob; 
    } pet_data; 

//enter data 
public: 
    void Read() 
    { 
     std::cout<<"Your pets first name: "; 
     std::cin>>pet_data.pet; 
     std::cout<<"Your last name: "; 
     std::cin>>pet_data.last_name; 
     std::cout<<"What kind of animal do you have: "; 
     std::cin>>pet_data.animal; 
     std::cout<<"Your animals dob: "; 
     std::cin>>pet_data.dob; 
     std::cout<<"Your animals color: "; 
     std::cin>>pet_data.color; 
    } 
}; 

#endif 
+0

*「C++沒有匿名結構。*」除非你考慮臨時對象。 :) – cdhowie 2014-09-03 19:46:48

+0

@cdhowie temporaries不是匿名結構。他們是未命名的結構。這是不同的概念。 – 2014-09-03 19:52:26

+0

爲cpp文件,我仍然會包含使用命名空間標準;? – user3326689 2014-09-03 19:56:18