我已被指示創建兩個類: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
一直在做研究和抵消的問題層出不窮,現在幾天一個時。 希望有人能來拯救我:)
是用友誼來解決這個問題,你需要的?你能否實施不使用友誼的解決方案? –
你爲什麼把理髮師的方法變成朋友?在該方法的定義中,理髮師調用公共方法,並且決不觸及客戶的任何私有或受保護部分。 – DrYap
你說得對,要求是通過朋友介紹獲得訪問權限。 我改變了代碼通過私有成員,而不是通過公開課 –