【问题标题】:" invalid operands of types 'int' and 'int* const'" error from function, from book“'int' 和 'int* const' 类型的无效操作数”来自函数的错误,来自书
【发布时间】:2017-01-20 03:10:25
【问题描述】:

我正在阅读“通过游戏编程开始 C++”一书。我已经完美地输入了这个提供的脚本(我什至将它与在线下载提供的脚本粘贴到它上面 - 并使用撤消/重做来比较每个字符 - 发现没有区别 - 除了行尾和函数名的第一个字符实际上大写)。尽管没有改变,提供的脚本编译得非常好,但我的没有(除非我复制/粘贴提供的脚本)。我在第二个函数中得到错误:GoodSwap()

#include<iostream>
using namespace std;

void BadSwap(int x, int y);
void GoodSwap(int* const pX, int* const pY);

int main(){
    int myScore = 150;
    int yourScore = 1000;
    cout << "Original Values" << endl;
    cout << "myScore  : " << myScore << endl;
    cout << "yourScore: " << yourScore << endl;

    cout << "Calling BadSwap()" << endl;
    BadSwap(myScore, yourScore);
    cout << "myScore  : " << myScore << endl;
    cout << "yourScore: " << yourScore << endl;

    cout << "Calling GoodSwap()" << endl;
    GoodSwap(&myScore, &yourScore);
    cout << "myScore  : " << myScore << endl;
    cout << "yourScore: " << yourScore << endl;

    return 0;
}

void BadSwap(int x, int y){
    int temp = x;
    x = y;
    y = temp;
}

void GoodSwap(int* const pX, int* const pY){
    int temp = *pX
    *pX = *pY;
    *pY = temp;
}

【问题讨论】:

  • 不,C++ 程序不是脚本。不,GoodSwap 非常糟糕。错误信息非常直白。
  • 我认为Good 在这里的意思是它可以工作。 :-)
  • int temp = *pX不管怎样,推荐C++书籍列here
  • @Danh ,我在这个问题上很认真。我花了 15 分钟查看每一行,并没有注意到——即使在复制/粘贴 :/ 之后。并感谢这本书的页面。我以前去过那里,但我最终选择了这本书,因为它以游戏概念为核心进行了教学——这很容易学习(我来自使用 C# 和 Unity,但想通过一个更“主流”的更畅销的语言)。

标签: c++ pointers


【解决方案1】:

您在GoodSwap() 的第一行错过了;

int temp = *pX  // There should be a `;`

修改后,你的程序可以在VS2015中编译了。

【讨论】:

  • 谢谢。在使用了 2 年之后,我来自 Python。这些 ';'看起来仍然有一半的时间是隐形的。我 +1 的回应,但我没有太多的声誉。我使用了带 gcc 编译器的 Notepad++。
  • gcc 也可以编译这个,使用命令gcc -lstdc++ yourCppFileName.cpp。编译 C++ 程序的更好方法是使用g++,它会自动链接到 C++ 运行时库。 g++ 命令与g++ yourCppFileName.cpp 一样简单。
  • 我目前使用的基本结构是“g++ -o main main.cpp”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 2015-09-26
  • 2013-02-12
相关资源
最近更新 更多