//成員函式做友元
//下面我也宣告了Show()為Per的友元,但是為什么還是報錯訪問不到m_A,
#include <iostream>
using namespace std;
class Son;
class Per
{
//宣告友元
friend void Son::Show();
public:
Per(){
m_A = 111;
m_B = 222;
}
int m_B;
private:
int m_A;
};
class Son
{
public:
Per *p;
Son(){
p = new Per();
}
void Show(){
//一下報錯仍然無法訪問私有成員
//cout << "訪問私有成員 = " << p->m_A << endl;
}
void Show1(){
cout << "訪問公有成員 = " << p->m_B << endl;
}
};
int main()
{
Son s;
s.Show();
s.Show1();
return 0;
}
uj5u.com熱心網友回復:
乾坤大挪移#include <iostream>
using namespace std;
class Son;
class Per;
class Son
{
public:
Per *p;
Son();
void Show();
void Show1();
};
class Per
{
//宣告友元
friend void Son::Show();
public:
Per(){
m_A = 111;
m_B = 222;
}
int m_B;
private:
int m_A;
};
Son::Son() {
p = new Per();
}
void Son::Show()
{
//一下報錯仍然無法訪問私有成員
cout << "訪問私有成員 = " << p->m_A << endl;
}
void Son::Show1(){
cout << "訪問公有成員 = " << p->m_B << endl;
}
int main()
{
Son s;
s.Show();
s.Show1();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/134413.html
標籤:C++ 語言
上一篇:二級C語言的程式設計題
下一篇:時間頻度和時間復雜度怎么算
