我一直試圖避免朋友的概念,因為它超越了封裝的目的。但是,我只是在嘗試這個概念,以下代碼無法編譯并出現以下錯誤:
main.cpp:29:28: error: ‘int A::a’ is private within this context
另一方面,如果我只是將 B 類放在 A 類之前并宣告 A 類,它運行良好。我在這里錯過了一些非常微不足道的東西嗎?
#include <iostream>
class A {
int a;
public:
A() { a = 0; }
// friend function
friend void B::showA(A& x);
};
class B
{
public:
void showA(A&);
private:
int b;
};
void B::showA(A& x)
{
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
uj5u.com熱心網友回復:
實際上,您在 A 類中使用 B 類,但正如您所見,在使用 B 之前未宣告 B。這導致了這樣的錯誤:
error: 'B' has not been declared
再遠一點
error: int 'A::a' is private within this context
因為第一個錯誤導致友誼關系沒有鏈接(因為 A::a 默認是私有的)
然后您可以嘗試 forward-declare B,如下所示
#include<..>
class B;
class A {
int a;
public:
A() { a = 0; }
// friend function
friend void B::showA(A& x);
};
class B{
...
}
...
這會產生錯誤error: invalid use of incomplete type 'class B',因為前向宣告僅表示稍后將定義特定類(此處class B),因此您可以參考它或擁有指向它的指標,但它沒有說明該類將具有哪些成員,因此編譯器無法知道你的未來 class B是否會有一個B::showA方法,因此錯誤,incomplete type error. 此時,編譯器不知道您未來的 B 類(在 A 類中使用)是否會有函式B::showA。
最簡單的解決方案是先宣告B然后A轉發宣告A(with class A;),如下所示。這樣,你告訴編譯器——這是我的class B宣告(它包含一個方法B::showA),它使用了一個A我將在稍后定義的類。由于不需要知道 的內容是什么A,它會編譯。
// as you use class A before it is declared, you need to forward declare it
class A;
class B
{
public:
void showA(A&);
private:
int b;
};
class A {
int a;
...
這將編譯并執行函式B::showA。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482910.html
上一篇:AngularIonicCapacitorBarcodeScannerPlugin無法在Web上運行
下一篇:如何在C 中定義編譯時三元文字?
