我尝试在VS 2008 SP1
C++
项目下进行以下编译,但friend class
语句似乎没有任何效果。 (请参阅上一个代码段中的错误消息。)
我对friend
定义做错了什么?
// EncryptionTypes.h file
#pragma once
//#include "Encryption.h" //adding this line doesn't help
using namespace crypto;
struct FILE_DATA_CACHE{
FILE_DATA_CACHE()
{
};
~FILE_DATA_CACHE()
{
}
friend class CEncryption;
private:
bool _isIndexFileUsed()
{
return bResult;
}
};
然后:
// Encryption.h
#pragma once
#include "EncryptionTypes.h"
namespace crypto
{
class CEncryption
{
public:
CEncryption(void);
~CEncryption(void);
private:
BOOL _openFile();
private:
FILE_DATA_CACHE gFData;
};
};
最后:
// Encryption.cpp
#include "StdAfx.h"
#include "Encryption.h"
namespace crypto
{
CEncryption::CEncryption(void)
{
}
CEncryption::~CEncryption(void)
{
}
void CEncryption::_openFile()
{
//The line below generates this error:
//1>.\Encryption.cpp(176) : error C2248: 'FILE_DATA_CACHE::_isIndexFileUsed' : cannot access private member declared in class 'FILE_DATA_CACHE'
//1> c:\users\blah-blah\EncryptionTypes.h(621) : see declaration of 'FILE_DATA_CACHE::_isIndexFileUsed'
//1> c:\users\blah-blah\EncryptionTypes.h(544) : see declaration of 'FILE_DATA_CACHE'
gFData._isIndexFileUsed();
}
};
答案 0 :(得分:2)
您有循环依赖问题。
Encryption.h需要FILE_DATA_CACHE
,它在EncryptionTypes.h中定义
EncryptionType.h需要CEncryption
,它在Encryption.h中定义。
幸运的是,您可以在EncryptionType.h中使用CEncryption
的前向声明。
将EncryptionType.h修改为:
// EncryptionTypes.h file
#pragma once
// Can't #include Encryption.h. That will lead to circular
// #includes.
namespace crypto
{
// Forward declaration of crypto::CEncryption
class CEncryption;
}
struct FILE_DATA_CACHE{
FILE_DATA_CACHE()
{
};
~FILE_DATA_CACHE()
{
}
friend class crypto::CEncryption;
private:
bool _isIndexFileUsed()
{
return bResult;
}
};