在以下給出,訪問乙我們可以用類B的成員函數和返回數據成員的私人數據成員,賦值給的數據成員的代碼在構造函數(轉換函數)內。但我無法這樣做。請建議一些幫助。其他方式可以使B的A類朋友,但需要通過構造函數訪問。訪問私有數據成員
#include <iostream>
using namespace std;
class B
{
int i_;
public:
B(int i = 3) : i_(i) {}
int give() { return i_; }
};
class A
{
int i_;
public:
A(int i = 0) : i_(i) { cout << "A::A(i)\n"; }
A(const B &b1) : i_(b1.i_) {} // Type casting using constructor
int display() { cout << i_; }
};
int main()
{
A a;
B b; // object is constructed
a = static_cast<A>(b); // B::operator A(), converting data member of class B to class A
a.display();
return 0;
}
感謝有用的信息。問題仍然是: prog.cpp:在構造函數 'A :: A(常數B&)': prog.cpp:18:32:錯誤:INT B :: I_'是私人此上下文 A內(常量B&B1):I_(b1.i_){} //使用構造 ^〜 prog.cpp類型鑄造:6:9:注:聲明爲專用這裏 INT I_; ^〜我想知道如何在沒有朋友聲明的情況下訪問B的i_。 – KnitahK
@KnitahK - 這不是論壇或調試服務。我用明顯的代碼指出了問題。如果您有*特定*問題,請發佈[mcve]。 – StoryTeller
@KnitahK - 這個錯誤表明你沒有使用'get()'。那麼你的代碼在這個問題上與錯誤有什麼關係? – StoryTeller