[英]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;
}
Changes are applicable only to class A, where actual value in class B is not changing. 更改仅适用于A类,而B类中的实际值未更改。 I tried static but its showing error. 我试过静态,但显示错误。
OUTPUT I'M GETTING : Inside set 100 inside show 100 inside show 0 inside show 100 输出我正在获取:内部设置100内部显示100内部显示0内部显示100
OUTPUT I WANT : Inside set 100 inside show 100 inside show 100 inside show 100 我要输出:内部设置100内部显示100内部显示100内部显示100
A class is not an object. 类不是对象。 It is a user defined data type which can be accessed and used by creating an instance of that class. 它是用户定义的数据类型 ,可以通过创建该类的实例来访问和使用。 An instance of the class is an object. 该类的一个实例是一个对象。
Now, in your main
function, when you instantiate an object of class A
by writing A a;
现在,在您的main
函数中,当您通过编写A a;
实例化A
类的对象时A a;
, the constructor of class A
instantiates the data member bb
(which is of type B
). , class A
的构造函数实例化数据成员bb
(类型B
)。 You then create another object of type B
in your main
function, by writing B b;
然后,通过编写B b;
在main
函数中创建另一个类型B
对象B b;
. 。 This instantiation of class B
has nothing to do with the data member bb
in your class A
. 类此实例B
无关的数据成员bb
在class A
。 To get your desired output, you would need a.bb.show()
. 要获得所需的输出,您需要a.bb.show()
。
To be clear: 要清楚:
struct Airplane {};
Airplane a1, a2, a3;
I have 3 airplanes, which are each an instantiation of the class Airplane
, 3 objects of type Airplane
. 我有3架飞机,其是每一个实例化class Airplane
,类型的3个对象Airplane
。 Changing a1
doesn't imply changing a2
and a3
. 更改a1
并不意味着更改a2
和a3
。
Try: 尝试:
int main()
{
A a;
B b;
a.func();
a.bb.show();
a.func2();
return 0;
}
You're calling show()
on wrong object. 您在错误的对象上调用show()
。 Since a
has it's own bb
, you need to use a.bb
to see change. 由于a
拥有自己的bb
,因此您需要使用a.bb
来查看更改。 b
in main
is different object (even if of the same class). main
对象中的b
是不同的对象(即使是同一类)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.