我想了解嵌套類中的友誼的概念,但我沒有正確理解概念。我已經寫了一個示例程序,瞭解它,但程序不工作嵌套類中的友誼C++
#include<iostream>
using namespace std;
class outerClass
{
private:
int a;
public:
class innerClass;
bool print(innerClass);
};
class innerClass
{
friend class outerClass;
private:
int b;
public:
innerClass() =default;
};
bool outerClass::print(outerClass::innerClass obj)
{
cout<<"Value of b in inner class is:"<<obj.b;
}
int main()
{
outerClass in;
outerClass::innerClass obj;
obj.b=5;
in.print(obj);
}
我得到以下錯誤:
try.cpp: In member function ‘bool outerClass::print(outerClass::innerClass)’:
try.cpp:26:6: error: ‘obj’ has incomplete type
try.cpp:11:15: error: forward declaration of ‘class outerClass::innerClass’
try.cpp: In function ‘int main()’:
try.cpp:34:28: error: aggregate ‘outerClass::innerClass obj’ has incomplete type and cannot be defined
當我通過互聯網上的文章閱讀我學到了以下幾點,請他們發表評論如果它們正確與否:
- innerClass默認情況下可以訪問outerClass的所有成員。
- 對於outerClass訪問innnerClass的私有成員,我們需要將outerClass作爲friend類到innerClass。
請幫忙指出代碼中的錯誤,以及如果我理解的觀點是正確的。
這裏的[關於內部類的定義,一個提示](http://stackoverflow.com/questions/8693590/how-to-make -an-inner-class-without-put-the-class-class-class-to-pare)外部類定義 – grek40