2011-12-13 128 views
1

我有以下代码:A类(即类B的成员)如何共享B类的私有成员?

Master.h

#ifndef MASTER_H 
#define MASTER_H 

class Master 
{ 
    friend class Friend; 

    public: 
     Master(void); 
     ~Master(void); 
     void CallFriendFunction(int largeData); 

    private: 
     int largeData; 

     //Want this class to share largeData; 
     Friend testFriend; 
}; 
#endif // MASTER_H 

Master.cpp

#include "Master.h" 

Master::Master(void) 
{ 
    //Inentionally left blank 
} 

Master::~Master(void) 
{ 
    //Intentionally left blank 
} 

void Master::CallFriendFunction(int largeData) 
{ 
    this->largeData = largeData; 
    this->testFriend.Test(this); 
} 

Friend.h

#ifndef FRIEND_H 
#define FRIEND_H 

#include "Master.h" 

class Friend 
{ 
    public: 
     Friend(void); 
     ~Friend(void); 

     void Test(Master* masterPtr); 
}; 

#endif // FRIEND_H 

Friend.cpp

#include "Friend.h" 
#include <iostream> 

Friend::Friend(void) 
{ 
    //Intentionally left blank 
} 

Friend::~Friend(void) 
{ 
    //Intentionally left blank 
} 

void Friend::Test(Master* masterPtr) 
{ 
    std::cout << masterPtr->largeData << std::endl; 
} 

我希望班级朋友能够分享师父的私人成员。但是,我无法获得此代码进行编译。我试过Forward Declaration和#includes,但是我开始进入循环依赖。当Friend类不是Master类的成员时,代码编译?

朋友类可以成为Master的成员并成为朋友吗? Friend类别还可以访问Masters私人会员吗?

+0

什么是编译器错误。 (C&P他们) – 111111 2011-12-13 17:24:52

+0

如果我使用上面的代码:在文件Master.h中:错误:'朋友'没有命名一个类型。如果#include“Friend.h”在Master.h中,我在Friend.h中遇到错误:error:'Master'尚未声明。然而#include“Master.h”在那里。 – 2011-12-13 17:26:54

回答

3

你需要以下包括转发声明:

在Master.h:

#include "Friend.h" 

在Friend.h:

class Master; 

在Friend.cpp:

#include "Master.h" 

推杆Friend.h中的前向声明可防止循环依赖。前向声明已经足够,因为您只声明Master*参数,而不使用其成员。

因为您声明的是Friend成员,所以您需要包含Friend.h,因为您要声明Friend成员,并且这需要一个完整的类型。

1

它看起来像你正在努力与循环依赖。请注意,为了制作一个friend,你不需要包含它。也就是说,在你的Master类中,你实例化了需要包含它作为头文件的朋友(否则编译器将全部是WTF?)。

然而,在friend.h你可以简单地向前声明大师班并没有直接包含它:

class Master; 

这是因为你没有试图实例化Master类,但用一个指针。