繁体   English   中英

C++ endl 带常量

[英]C++ endl with constants

我只是想让自己熟悉从 Java 迁移而来的 C++ 的基础知识。 我刚刚编写了这个功能禁欲程序,遇到了一个错误test.cpp:15: error: expected primary-expression before '<<' token我不知道为什么。

有人愿意解释为什么endl不能使用常量吗? 代码如下。

//Includes to provide functionality.
#include <iostream>

//Uses the standard namespace.
using namespace std;

//Define constants.
#define STRING "C++ is working on this machine usig the GCC/G++ compiler";

//Main function.
int main()
{
  string enteredString;

  cout << STRING << endl;
  cout << "Please enter a String:" << endl;
  cin >> enteredString;
  cout << "Your String was:" << endl;
  cout << enteredString << endl;

  return(0);
}

您的#define末尾有一个分号。 这成为宏的一部分,因此预处理代码如下所示:

cout << "C++ is working on this machine usig the GCC/G++ compiler"; << endl;

删除分号,你应该没问题。


PS:为此使用实常数而不是依赖预处理器通常是一个更好的主意:

const char *STRING = "C++ is working on this machine usig the GCC/G++ compiler";

你有一个; 在您的预处理器定义中。 请注意, #DEFINE STRING x只是将整个 x 语句(包括; )复制到引用它的位置。

此外,预处理器常量不是语言常量。 你应该使用const string STRING("C++ is working on this machine usig the GCC/G++ compiler");

您的#define末尾有一个分号 - 这将被替换到您的代码中,给出。

cout << "C++ is working on this machine usig the GCC/G++ compiler"; << endl;

因为您在 STRING 之后有一个分号。 删除它并尝试一下...

删除; STRINGS定义中

删除

#define STRING "C++ is working on this machine usig the GCC/G++ compiler"

删除; #define STRING末尾,然后重试。

define 是一个预处理器指令。 这将替换定义宏之后的所有内容,在本例中为 STRING。 因此,删除最后一个分号 (;),该分号 (;) 在违规行中展开时放置语句结束标记。

暂无
暂无

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

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