两个单独文件之间的 C++ 友元函数声明

标签 c++ compiler-errors

我被指示创建两个类:Customer 和 Barber, Barber 应该有一个函数:cutHair() 可以改变 Customer 中私有(private)成员 hairLength 的值。

客户.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

理发师.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() 的实现以利用友元声明,而不是通过它的公共(public)访问器方法访问类 Customer 的私有(private)成员

#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; 
}

客户.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;
}

尝试构建时出现错误消息

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

几天来一直在研究和取消一个接一个的问题。 希望有人能来救我:)

最佳答案

你在这里有循环依赖。您包括 customer.h 中的 barber.h 和 barber.h 中的 customer.h。

在barber.h中使用

class Customer;

代替

#include "customer.h"

关于两个单独文件之间的 C++ 友元函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7316513/

相关文章:

java - 如何在服务中使用 FirebaseListAdapter<String>?

c++ - CUDA 对大量线程的奇怪行为

c++ - double C++

c++ - 这不是一个真正的指针?

c++ - 使用 Visual Studio 2010 时出现错误/不正确的 C2248 错误

module - 编译Ocaml游戏时未绑定(bind)模块事件错误

mongodb - Playframework 2.3x : scala. concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent]

c++ - 为什么变量声明和for循环的条件一样好用?

c++ - 你能用 lambda 比较器交换 std::queue 吗?

list - 有效地合并两个列表