如何转换一个类方法以修改另一个类的私有元素?



我有一个类 B 的指针属性为 A 类,其方法将指针属性分配给另一个类 A 的变量。然而,这个变量是私有的,因此分配变量会产生错误。如何解决此问题?

#include<iostream>
using namespace std;
class A {
private :
int x;
public:
A(int);
~A();
};
class B {
private :
A * pA;
int y;
public:
B(int, int);
~B();
void imprimer();
};
void B::imprimer() {
cout << "B::imprimer: " << pA->x << " " << y << endl;
}

main()
{
B to(1, 2);
to.imprimer(); //instruction (1)
}

给出以下结果:

$ g++ td4Exercice1_2.cpp -o td4Exercice1_2
td4Exercice1_2.cpp: In member function ‘void B::imprimer()’:
td4Exercice1_2.cpp:7:6: error: ‘int A::x’ is private
int x;
^
td4Exercice1_2.cpp:24:33: error: within this context
cout << "B::imprimer: " << pA->x << " " << y << endl;

你缺少的是类A 的类 get()set(int)方法您没有声明 B 类是 A 类的朋友。

A的 x 是类 A 中的私有变量。只有类 A 可以修改其变量,除非您执行一些操作。

您声明 B 类是 A 类的朋友。

class B; // you must 'declare Class B before Class A for this to work
class A {
friend class B;
private :
int x;
public:
A(int);
~A();
};

这将允许B类完全访问A类中的任何内容,这是一个糟糕的设计。

有复杂的方法可以做到这一点,如"C++ Primer",S. Lippman所示,允许"<<"运算符与类交朋友以进行输出。QED。

执行此操作的侵入性最小的方法是在类 A 中创建一个新方法。

class A {
private :
int x;
public:
A(int);
~A();
int getX( void) { return( x ) };
};
void B::imprimer() {
cout << "B::imprimer: " << pA->getX() << " " << y << endl;
}

现在,您可以获取 A::x 的值,但无法更改它。

这确实会导致一些更大的设计问题,因为您现在拥有 A::x 的最后一个值,尽管可能不是 A::x 的当前值。

进一步研究使用"friend"和"<<">>"运算符将向您展示一种更好的方法,具体取决于您的程序的大局。

最新更新