[英]Compile error when creating two classes, each of which contains a member function to access the other class
我想創建兩個類,每個類都包含一個成員函數,該成員函數可以訪問另一個類中的私有成員。 我的代碼如下:
#include <iostream>
using namespace std;
class B;
class A {
int a;
public:
void init();
void printB(B*);
friend void B::printA(A*);
};
class B {
int b;
public:
void init();
void printA(A*);
friend void A::printB(B*);
};
void A::init() {
a = 10;
}
void A::printB(B* bp) {
cout << bp->b << endl;
}
void B::init() {
b = 999;
}
void B::printA(A* ap) {
cout << ap->a << endl;
}
int main() {
A x;
B y;
x.init();
y.init();
x.printB(&y);
y.printA(&x);
}
使用g++
編譯時,出現錯誤
twoclassTest.cpp:11:26: error: invalid use of incomplete type ‘class B’
twoclassTest.cpp:4:7: error: forward declaration of ‘class B’
twoclassTest.cpp: In member function ‘void B::printA(A*)’:
twoclassTest.cpp:7:6: error: ‘int A::a’ is private
twoclassTest.cpp:35:14: error: within this context
看來編譯器在看到class B
時到底不知道什么
friend void B::printA(A*)
我不知道該問題的解決方案,所以我必須像這樣重寫class A
類
class A {
int a;
public:
void init();
void printB(B*);
friend class B;
};
這有效,但是實際上我不希望B
每個成員函數都能夠訪問A
的私有成員。 那么這個問題有什么解決辦法嗎?
在到達的點:
friend void B::printA(A*);
編譯器無法知道B
具有成員函數printA
。 這就是導致錯誤的原因。 最好的解決方案是將這兩個類解耦並完全刪除依賴性。
就像Jeffery所說的那樣,麻煩在於,編譯器無法知道B::printA()
在嘗試將其聲明為朋友時就存在。
如果你真的想要做的事情這樣,您就可以通過全班宣布繞過它B
作為朋友A
,即替代friend void B::printA(A*)
與friend class B
。
我認為這個故事的寓意是“如果傷了就不要做”! :-)
在C ++中,“事物”是一類。 在這種情況下, A
和B
之間的接口可以表示為Shared
類。
當然,您甚至可以進一步定義兩個接口ASharedWithB
和BSharedWithA
。
#include <iostream>
using namespace std;
class A;
class B;
class Shared
{
public:
static void print(A* a);
static void print(B* b);
};
class B;
class A {
int a;
public:
void init();
void printB(B*);
friend class Shared;
};
class B {
int b;
public:
void init();
void printA(A*);
friend class Shared;
};
void A::init() {
a = 10;
}
void A::printB(B* bp) {
Shared::print(bp);
}
void B::init() {
b = 999;
}
void B::printA(A* ap) {
Shared::print(ap);
}
void Shared::print(A* ap)
{
cout << ap->a << endl;
}
void Shared::print(B* bp)
{
cout << bp->b << endl;
}
int main() {
A x;
B y;
x.init();
y.init();
x.printB(&y);
y.printA(&x);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.