简体   繁体   English

C ++如何直接调用在类中定义的方法,其中仅对该类的引用由另一个函数返回

[英]C++ how to call a method defined in a class directly where only the reference to the class is returned by another function

In my program, I have a grid class (eg myGrid ) and I could obtain a reference to a cell (a class) by overloading the operator() . 在我的程序中,我有一个网格类(例如myGrid ),并且可以通过重载operator()获得对单元格(一个类)的引用。 My problem is each time I call this myGrid(x, y) which returns a reference to a cell, I need to claim a cell reference. 我的问题是每次我调用此myGrid(x, y)返回一个对单元格的引用时,都需要声明一个单元格引用。

 cell& myCell = myGrid(x,y);
 myCell.status = currentStatus; 

I got an error by doing this: 我这样做有一个错误:

(myGrid(x,y)).status = currentStatus;

I need to use the function defined in cell very frequently. 我需要经常使用单元格中定义的功能。 Thus, each time I need to claim a cell reference which makes my code look urgly. 因此,每次我需要声明一个单元格引用时,都会使我的代码显得仓促。 Is there any elegant way to solve the problem? 有什么优雅的方法可以解决问题吗? Thanks very much. 非常感谢。 Cheers! 干杯!

Sorry. 抱歉。 There is a typo. 有一个错字。 Let's assume status is a public varible in cell and assume currentStatus is a variable of the same type as status. 假设status是单元格中的公共变量,并假设currentStatus是与status相同类型的变量。

Grid is a predefined class and I don't have the right to modify it. 网格是预定义的类,我无权对其进行修改。 It returns a reference to cell. 它返回对单元格的引用。 Eg cell& operator()(int x, int y) 例如cell&operator()(int x,int y)

Sorry for the chaos. 对不起,混乱。 myGrid(x,y).status works. myGrid(x,y).status工作。 I made a mistake somewhere before. 我之前在某处犯了一个错误。 When I complied it, the error occurred in this line. 当我编译它时,此行中发生了错误。 Thanks very much! 非常感谢!

the object of function-myGrid(x,y) return ,maybe out of scope. 函数myGrid(x,y)的对象返回,可能超出范围。 I mean, the object you return may be a local variable. 我的意思是,您返回的对象可能是局部变量。

How your operator() defined (signature)? 您的operator()如何定义(签名)? What is the signature of status ? status的标志是什么? They should be cell& operator() (int x, int y); 它们应该是cell& operator() (int x, int y); and int& status(); int& status(); . Provide minimal example that doesn't work. 提供无效的最小示例。

And the best way and elegant is to use explicit methods: 最好的方法是使用显式方法:

myGrid.GetCell(x, y).SetStatus(s);

This is much more readable and supportable. 这更具可读性和可支持性。 Also, using getter/setter instead of returning a reference may allow you control point where value changed - you may log there or set a breakpoint. 同样,使用getter / setter而不是返回引用可以使您控制更改值的位置-您可以在此处记录或设置断点。 Returning reference is poor practice - you may never be sure will it be changed or only read after. 返回参考文献的做法不佳-您可能永远无法确定是否会对其进行更改或仅在以后阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM