[英]Access data member of a member function from one class to another class's member function
[英]change value of data member of one class from another class
#include <iostream>
using namespace std;
class B{
public:
int x;
void setx(int a){
x =a;
cout<<"Inside set "<<x<<endl;
}
void show();
};
void B::show(){
cout<<"inside show "<<x<<endl;
}
class A{
public:
void func();
void func2();
B bb;
};
void A::func(){
bb.setx(100);
bb.show();
}
void A::func2(){
bb.show();
}
int main()
{
A a;
B b;
a.func();
b.show();
a.func2();
return 0;
}
更改仅适用于A类,而B类中的实际值未更改。 我试过静态,但显示错误。
输出我正在获取:内部设置100内部显示100内部显示0内部显示100
我要输出:内部设置100内部显示100内部显示100内部显示100
类不是对象。 它是用户定义的数据类型 ,可以通过创建该类的实例来访问和使用。 该类的一个实例是一个对象。
现在,在您的main
函数中,当您通过编写A a;
实例化A
类的对象时A a;
, class A
的构造函数实例化数据成员bb
(类型B
)。 然后,通过编写B b;
在main
函数中创建另一个类型B
对象B b;
。 类此实例B
无关的数据成员bb
在class A
。 要获得所需的输出,您需要a.bb.show()
。
要清楚:
struct Airplane {};
Airplane a1, a2, a3;
我有3架飞机,其是每一个实例化class Airplane
,类型的3个对象Airplane
。 更改a1
并不意味着更改a2
和a3
。
尝试:
int main()
{
A a;
B b;
a.func();
a.bb.show();
a.func2();
return 0;
}
您在错误的对象上调用show()
。 由于a
拥有自己的bb
,因此您需要使用a.bb
来查看更改。 main
对象中的b
是不同的对象(即使是同一类)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.