2013-03-10 81 views
0

因此,在單獨的頭文件中有兩個類別朋友函數,預期之前的主表達式。代幣

客戶。 h

using namespace std; 
#include <iostream> 

class Customer{ 
    friend void Display(); 
private: 
    int number, zipCode; 
public: 
    Customer(int N, int Z){ 
    number = N; 
    zipCode = Z; 
    } 
}; 

市。 h using namespace std; 的#include 的#include 「Customer.h」

class City{ 
    friend void Display(); 
private: 
    int zipCode; 
    string city, state; 
public: 
    City(int Z, string C, string S){ 
     zipCode = Z; 
     city = C; 
     state = S; 
    } 
}; 

我的main.cpp如下

#include "City.h" 
#include "Customer.h" 

void Display(){ 
     cout<<"Identification Number: "<<Customer.number<<endl 
       <<"Zip Code: "<<Customer.zipCode<<endl 
       <<"City: "<<City.city<<endl 
       <<"State: "<<City.state<<endl; 
    } 


int main() { 
    Customer A(1222422, 44150); 
    City B(44150, "Woklahoma", "Kansas"); 

    Display(); 

} 

我擅長與C的基礎++,但是這是我不明白,所以我的具體問題是....爲什麼在四大行我的顯示功能的該編譯器告訴我「錯誤:預期前主表達式令牌‘’」

由於提前,MACAIRE

回答

1

Customer是一種類型。你需要一個這種類型的對象來訪問它的number成員(並且對於其餘的行也是如此)。

你可能意味着採取CustomerCity作爲參數傳遞給Display

void Display(Customer customer, City city){ 
    cout<<"Identification Number: "<<customer.number<<endl 
      <<"Zip Code: "<<customer.zipCode<<endl 
      <<"City: "<<city.city<<endl 
      <<"State: "<<city.state<<endl; 
} 

然後通過你的CustomerCity對象是函數:

Display(A, B); 
+0

哎呀,我看到了,我試圖訪問這些字段,就好像它們是靜態的。 – 2013-03-10 20:28:09

1

你正試圖從一個類名

Customer.number 

你不能這樣做,訪問數據成員。你需要一個Customer實例:

Customer c; 
std::cout << c.number; 

你可能想改變Display()

void Display(const Customer& c); 

然後使用它是這樣的:

Customer A(1222422, 44150); 
Display(A); 

,同樣爲City

+0

感謝我跟着你和sftrabbit說了什麼,並使用我剛剛瞭解到的「前向聲明」功能,並且這一切都非常完美。 – 2013-03-10 20:33:27