【问题标题】:Further Explanation needed: Initial value of reference to non-const must be a lvalue需要进一步解释:对非常量的引用的初始值必须是左值
【发布时间】:2016-11-27 07:10:33
【问题描述】:

项目范围:学术

预期目的:有一个用于项目提交的 GUI。这个问题涉及使图形窗口的定义区域可点击。我不熟悉其他图形库。

我在该站点的其他地方查看并阅读了有关此错误的类似帖子:“对非常量的引用的初始值必须是左值。”我真的需要一些进一步的解释来解决这个问题:

    #include "graph1.h"`
 displayPNG("solve.png", 560, 120);
int x2 = 560 + 54; 
  int x1 = 560;
  int y1 = 120;
  int y2 = 291 + 120;
  const int * xSolv2 = &x2;
  const int * xSolv1 = &x1;
  displayPNG("exit.png",545,415);

  //Game (loop) play for buttons, options & clickables. 
  //while (true){
   if (leftMouse((xSolv2 > xSolv1) && (x1 < &x2), (&y2 > &y1) && (&y1 < &y2)))  //error: "Initial value of reference to non-const must be an lvalue."
   {
      cout << "Test button functions properly" << endl;
   }

我尝试了以下变体,但没有成功。

//shortened for brevity purposes. 
bool function (&x,&y) 
bool function (*x,*y) // I had created some pointer var(s) earlier and initialized them. 

bool function(x, y)

如果有人有在graphicLib2015.lib 中使用“graph1.h”的经验,我很想学习。

【问题讨论】:

  • x1 &lt; &amp;x2 为什么要将值与地址进行比较?
  • (&amp;y2 &gt; &amp;y1) &amp;&amp; (&amp;y1 &lt; &amp;y2)这也是(&amp;y1 &lt; &amp;y2)的一种很冗长的说法
  • 小建议:例如,如果您定义x2 = x1 + 54;,代码将更容易更改。
  • 谷歌搜索“graphicLib2015”时的感觉让我回到了同样的 StackOverflow 问题

标签: c++ user-interface graphics lvalue


【解决方案1】:

我可能是错的,但你可以消除 xSolv1xSolv2。如果您需要指向x1 的指针,您可以提供&amp;x1

指针是 !!fun!! 的重要来源!和意想不到的行为。当您说(xSolv2 &gt; xSolv1) 时,您是在比较x1x2 的内存位置!这几乎肯定不是你想要的☺

正如你所说的签名是bool leftMouse(int &amp;x, int &amp;y),你可能想做类似的事情......

int x;
int y;
leftMouse(x, y); // probably will update x and y with the mouse position
if (x1 < x && x < x2 && y1 < y && y < y2 ) {
  // then the mouse is in box
}

【讨论】:

  • 实际上所有的(&amp;foo &lt; &amp;bar) 比较都有点奇怪——它们又是在比较内存地址位置。 leftMouse 有什么论据??
  • bool leftMouse(int &x, int &y)
  • 好的,所以我猜你给它两个ints,它会更新它们。然后检查它们是否在您定义的区域内。
  • 我曾经尊重过他们,但仍然没有采取。
  • 我已经更新了我的答案(再次)——如果一个函数将引用作为参数,你不需要取消引用它。
猜你喜欢
  • 2013-07-20
  • 1970-01-01
  • 2022-11-30
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 2021-06-15
相关资源
最近更新 更多