![](/img/trans.png)
[英]Is it possible to have an instance of a class as a data member of another class?
[英]I want to change the parent's member data to an instance of another class
在C ++中,我有一個類A
和一個類B
在類A
,有一個對象(類B
),我想在類B
的對象中更改類A
成員數據。 我怎樣才能做到這一點 ?
我想做這個:
class A {
public:
A() {
new B(this);
}
private:
int i;
};
class B {
public:
B(A* parent) {
this->parent = parent;
}
change() {
parent->i = 5;
}
private:
A* parent;
};
在聲明A
類時A
您需要將B
類定義為朋友:
friend class B;
class A {
friend class B;
private:
int i;
public:
A() : i(0) {
new B(this);
}
};
與其將B設置為A的朋友類,不如將其保留為封裝,更好的方法是在A類中添加setter方法。
然后,您的A類看起來像這樣:
class A {
public:
A() {
new B(this);
}
void set_i(int value)
{
i = value;
}
private:
int i;
};
然后在您的B類實現中,調用set_i()。
class B {
public:
B(A* parent) {
this->parent = parent;
}
change() {
parent->set_i(5);
}
private:
A* parent;
};
這樣,您就不會在B類中公開和依賴A類的私有實現細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.