2011-09-06 79 views
1

我已被指示創建兩個類:Customer和Barber, 理髮師應該有一個函數:cutHair(),它可以更改Customer中私有成員hairLength的值。兩個獨立文件之間的C++好友函數聲明

Customer.h

#ifndef CUSTOMER_H 
#define CUSTOMER_H 
#include "barber.h" 
#include <iostream> 
#include <string> 
using namespace std; 

class Customer{ 
    public: 
     friend void Barber::cutHair(Customer &someGuy); 
     Customer(string name, double hairLength); 
     string getName(); 
     double getHair(); 
     void setHair(double newHair); 
    private: 
     string name; 
     double hairLength; 
}; 
#endif 

Barber.h

#ifndef BARBER_H 
#define BARBER_H 
#include <iostream> 
#include <string> 
#include "customer.h" 
using namespace std; 
class Customer; 
class Barber{ 
    public: 
     Barber(string barberName); 
     void cutHair(Customer &someGuy); 
    private: 
     string name; 
     double takings; 
}; 
#endif 

barber.cpp 編輯:我改變cutHair()的實施,充分利用友元聲明,而不是訪問私有客戶通過它的公共存取方法的成員

#include "barber.h" 
#include <string> 

Barber::Barber(string barberName){ 
     name = barberName; 
     takings = 0; 
} 
void Barber::cutHair(Customer &someGuy){ 
     takings += 18; 
     someGuy.hairLength = someGuy.hairLength * 80/100; 
} 

customer.cpp中

#include "customer.h" 
#include <string> 

Customer::Customer(string customerName, double custHairLength){ 
     name = customerName; 
     hairLength = custHairLength; 
} 
double Customer::getHair(){ 
     return hairLength; 
} 
void Customer::setHair(double newLength){ 
     hairLength = newLength; 
} 

attemping打造我得到錯誤信息

customer.h(10): error C2653: 'Barber' : is not a class or namespace name 

一直在做研究和抵消的問題層出不窮,現在幾天一個時。 希望有人能來拯救我:)

+0

是用友誼來解決這個問題,你需要的?你能否實施不使用友誼的解決方案? –

+3

你爲什麼把理髮師的方法變成朋友?在該方法的定義中,理髮師調用公共方法,並且決不觸及客戶的任何私有或受保護部分。 – DrYap

+0

你說得對,要求是通過朋友介紹獲得訪問權限。 我改變了代碼通過私有成員,而不是通過公開課 –

回答

0

Barber.h你正在轉發聲明客戶(class Customer;)和包括#include Customer.h"。嘗試刪除包含。當然,你必須添加在您Barber.cpp

+0

大來訪問它,得到真正的幫助! 更充滿希望享受現在的C++編程:) –

3

您在這裏有循環依賴。您可以在barber.h中包含customer.h和customer.h中的barber.h。

在barber.h使用

class Customer; 

,而不是

#include "customer.h" 
+0

謝謝,這是有益的。 這是你的建議和Drahakar的 的組合說我必須添加包括在您的Barber.cpp –

+0

嗨,很高興聽到這一點;-)如果它幫助你,請接受答案。 –

+0

哦,謝謝你指出, 我忘了這個功能,它是我的第一篇文章:) 爲了準確性,我接受了Drahakar的建議,因爲它提到了這兩個問題。 是否可以接受多個答案? –

0

當你正在做一個向前聲明,如Barber.hclass Customer,你告訴編譯器,如果你看到它的名字客戶忽略只要你不需要知道對象的大小,現在就可以聲明它。然而,在你的情況,當你宣佈你正在使用的參數實際Customer對象CutHair功能。如果您在某種程度上改變了代碼,具有指針Customer作爲參數,並擺脫列入依賴,你的代碼進行編譯。

我還建議您的情況下,如果您定義了setHair函數,則不需要朋友函數,除非您有充分理由不具備該函數。