通过引用将对象传递到类中
是的,我将尝试在这里解释我的想法。 我现在有两个班级,分别是class1和class2。 我想通过引用将 class2 的对象传递给 class1 的对象。
但我只想将其传入一次,而不是每次调用方法时都必须将其传入。
我尝试过创建指针,也尝试过创建引用,但无济于事。 任何帮助表示赞赏。
#include <iostream>
using namespace std;
class myclass
{
private:
int i;
public:
myclass()
{
}
void method()
{
cout << "Enter num: ";
cin >> i;
}
void display()
{
cout << i;
}
};
class relatedclass
{
public:
relatedclass(myclass ob)
{
pmc = &ob;
}
myclass *pmc;
};
void main()
{
myclass mc;
relatedclass rc(mc);
//display value of mc.i
mc.display();
cout << endl;
//ok lets change the i variable
rc.pmc->method();
cout << endl;
//display new value of mc.i
mc.display();
cout << endl;
}
对于测试日期,我输入了 50,并且我预计 mc 对象会更新,现在 i 等于 50。
Right Ill try to explain my thinking here.
I have two classes at the moment, known as class1 and class2.
I want to pass an object of class2 into an object of class1, by reference.
but i want to only have to pass it in once, rather than having to pass it in every time a method is called.
I've tried creating a pointer and I have tried creating a reference, but to no avail.
Any help appreciated.
#include <iostream>
using namespace std;
class myclass
{
private:
int i;
public:
myclass()
{
}
void method()
{
cout << "Enter num: ";
cin >> i;
}
void display()
{
cout << i;
}
};
class relatedclass
{
public:
relatedclass(myclass ob)
{
pmc = &ob;
}
myclass *pmc;
};
void main()
{
myclass mc;
relatedclass rc(mc);
//display value of mc.i
mc.display();
cout << endl;
//ok lets change the i variable
rc.pmc->method();
cout << endl;
//display new value of mc.i
mc.display();
cout << endl;
}
for the test date I entered 50, and i expected the mc object to be updated and i would now equal 50.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EDIT: In your example, in the
relatedclass
constructor, you take the address of a local variable. That variable will be destroyed when the constructor returns. After that, yourpmc
pointer points to a destroyed object, which is a no-no.将此行更改
为:
EDIT: In your example, in the
relatedclass
constructor, you take the address of a local variable. That variable will be destroyed when the constructor returns. After that, yourpmc
pointer points to a destroyed object, which is a no-no.Change this line:
to this
您可以像这样在 class1 中保存 class2 的成员变量,并使用 set 变量设置该成员变量。
You can hold a member variable of class2 in class1 like this and have a set variable set the member variable.