保持健康和友谊是两个完全不同和不相关的东西。
A
是否为B
的朋友并不重要。这只是您的设计选择,无论您是想要封装对A
中的B
成员的访问权限,还是希望允许调用者直接访问B
获取者/设置者。
至于修改对象而言,任何干将应该声明为const
,使他们能够在const
和非const
对象都被调用(因为他们没有修改他们从阅读的对象),但如果你要能够修改对象的成员,那么你必须通过非const
指针(或非const
参考)访问对象:
class B;
class A {
private:
std::vector<B*> m_list;
public:
// this can be called on a non-const A, and
// the B members can be read and modified...
B* getB(int index) {
return m_list[index];
}
// this can be called only on a const A, and
// the B members can be read but not modified...
const B* getB(int index) const {
return m_list[index];
}
/* optional:
int getB_A(int index) const {
return getB(index)->getA();
}
float getB_B(int index) const {
return getB(index)->getB();
}
long getC(int index) const {
return getB(index)->getC();
}
void setB_A(int index, int value) {
getB(index)->setA(value);
}
void setB_B(int index, float value) {
getB(index)->setB(value);
}
void setB_C(int index, long value) {
getB(index)->setC(value);
}
*/
};
class B {
private:
int a;
float b;
long c;
public:
int getA() const {
return a;
}
float getB() const {
return b;
}
long getC() const {
return c;
}
void setA(int value) {
a = value;
}
void setB(float value) {
b = value;
}
void setC(long val) {
c = val;
}
};
或者:
class B;
class A {
private:
std::vector<B*> m_list;
public:
// this can be called on a non-const A, and
// the B members can be read and modified...
B* getB(int index) {
return m_list[index];
}
// this can be called only on a const A, and
// the B members can be read but not modified...
const B* getB(int index) const {
return m_list[index];
}
int getB_A(int index) const {
return getB(index)->a;
}
float getB_B(int index) const {
return getB(index)->b;
}
long getC(int index) const {
return getB(index)->c;
}
void setB_A(int index, int value) {
getB(index)->a = value;
}
void setB_B(int index, float value) {
getB(index)->b = value;
}
void setB_C(int index, long value) {
getB(index)->c = value;
}
};
class B {
private:
int a;
float b;
long c;
friend class A;
};
这并不完全清楚你问的是什么,你能产生一个代码[mcve]来说明你的问题吗? – George
“通过使用friend关键字修改私人成员是否是好习惯?” - 第 – KonstantinL
“我可以删除返回的指针上的常量” - 这比“朋友”更糟。 – KonstantinL