朋友功能无法访问私人会员

时间:2017-04-11 00:30:02

标签: c++

所以我在2个朋友函数上声明,所以他们可以访问其他2个类:

crash

它在每个头文件中,在公共场合。

现在,当我在main.cpp中编写函数时,在编写函数'Check'时,我可以访问每个类(worker和student)的私有变量,但是当我写'Birthday'函数时,也在main中。 cpp,我只能访问工人私人,而不是学生。这是为什么?我需要做什么?

Worker.H

    friend int Birthday(Student** student, Worker** worker, int sizeS, int sizeW, MyDate date);
    friend bool Check(Student** student, Worker** worker, int sizeS, int sizeW, char* ID);

Student.H

#ifndef  Worker
#include "MyDate.h"
class Student;
class Worker {
private:
    char* name;
    char ID[9];
    MyDate birthdate;
    float wage;
    int workH, extraH;
public:
    Worker(char*, char*, MyDate, int);
    Worker(const Worker&);
    ~Worker();
    void Print();
    float Salary();
    void Set(int, int);
    friend int Birthday(Student** student, Worker** worker, int sizeS, int sizeW, MyDate date);
    friend bool Check(Student** student, Worker** worker, int sizeS, int sizeW, char* ID);
};
#endif // ! Worker

main.cpp的一部分(未完成)

#ifndef Student
#include "MyDate.h"
#include <iostream>
using namespace std;
class Worker;
class Student {
private:
    char* name;
    char ID[9];
    MyDate birthdate;
    int courses;
    int* list;
public:
    Student(char*, char*, int, int, int);
    Student(const Student&);
    ~Student();
    void Print();
    float Average();
    bool CheckS(int);
    friend int Birthday(Student** student, Worker** worker, int sizeS, int sizeW, MyDate date);
    friend bool Check(Student** student, Worker** worker, int sizeS, int sizeW, char* ID);
};
#endif

由于

1 个答案:

答案 0 :(得分:0)

更有可能的是,由于撤消了if语句,你的第二种方法的实现没有编译。

见下文一切正常...... 的 Student.h

#ifndef STUDENT_H
#define STUDENT_H

class Worker;

class Student {
    int pks=0;
public:
    Student(){};
    ~Student(){};

    friend int Birthday(Student s, Worker w);
    friend bool Check(Student s, Worker w);
};
#endif

<强> Worker.h

#ifndef WORKER_H
#define WORKER_H

class Student;

class Worker {
    int pkw=1;
public:
    Worker(){};
    ~Worker(){};

    friend int Birthday(Student s, Worker w);
    friend bool Check(Student s, Worker w);
};
#endif

最终 main.cc

#include "Student.h"
#include "Worker.h"

int Birthday(Student s, Worker w)
{return s.pks;}

bool Check(Student s, Worker w)
{return w.pkw==1;}

使用命令测试:

g++ main.cc -c