簡體   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