C ++类成员通过引用(C++ class member by reference)

[db:摘要]

C ++类成员通过引用(C++ class member by reference)

大家好,有人可以帮帮我吗? 我有一个班级成员参考:

class name{ int& broj; string ulica;

并有构造函数:

public: kuca(int b, string s) :broj(b) { ulica = s; }

和输出的信息类

void info(){ cout << broj << ulica << endl; } };

当我创建对象并尝试输出它

int isbn = 1; name a(isbn, "text"); a.info();

作为参考值我似乎得到垃圾/随机值,而其他属性写得很好:

-858993460 text

Hello can anyone help me with this? I have a class with member by reference:

class name{ int& broj; string ulica;

And have constructor:

public: kuca(int b, string s) :broj(b) { ulica = s; }

and info class for output

void info(){ cout << broj << ulica << endl; } };

When i create object and try to output it

int isbn = 1; name a(isbn, "text"); a.info();

for reference value i am getting junk/random value it seems, while other attribute is written fine:

-858993460 text

最满意答案

更改您的ctor签名如下:

kuca(int& b, string s) :broj(b)

注意int&而不是int 。 然后,参数b将引用变量isbn而不是某个调用堆栈位置。

应该注意的是带有原始签名

kuca(int b, string s) : broj(b)

你正在参考堆栈上传递的副本参数。 因此,当调用info()方法时, broj引用调用堆栈上的位置而不是变量isbn 。 这就是为什么它似乎打印出“随机”值。

change your ctor signature as follows:

kuca(int& b, string s) :broj(b)

note the int& instead of int. Then, the parameter b will refer to the variable isbn rather than to some call stack location.

It should be noted that with the original signature

kuca(int b, string s) : broj(b)

you're taking a reference of the parameter that's a copy passed on the stack. So, when the info() method is called, then broj refers to a location on the call stack rather than to the variable isbn. That is why it appears to print a "random" value.

发布者:admin,转转请注明出处:http://www.yc00.com/web/1690611581a378969.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信