我有一个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;
答案 0 :(得分:0)
您缺少的是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类中的任何内容。 BUT 这是 POOR 设计。
有很多方法可以做到这一点,如“C ++ Primer”,S。Lippman所示,允许“&lt;&lt;&lt;&lt;&lt;操作员将该类输出为朋友。 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的当前值。在开始使用x的值之前,可能已经修改了x。
进一步研究将'friend'与“&lt;&lt;”结合使用“&GT;&gt;” 中运营商将根据您的计划的大图片向您展示更好的方式。