【发布时间】:2016-08-31 10:48:37
【问题描述】:
为什么这段代码不能编译?
#include <iostream>
using namespace std;
#define $_ cout << "Use '$_' befor commands to execute them";
#define $_Help cout << "Type $_ befor each command to execute it, type the command without $_ to view information about the command. Commands: Help, Quiz";
#define $_Quiz int quiz(){int score = 0; std::string name; std::string quest1; cout << "What is your name? "; cin >> name; cout << "Hello, " << name << endl; score++; cout << "Is pi > 3.14159? yes or no? "; cin >> quest1; if (quest1 == "yes"){cout << "Correct!"; score++;}else if (quest1 == "no"){cout << "Incorrect, pi has more numbers that just 3.14159.";}cout << " Your score is, " << score << endl; return 0;};
#define Help cout << "Display all of the commands";
#define Quiz cout << "A simple quiz(only one question right now)";
#define testForInputComm if(termComms == "$_Help"){$_Help;}else if(termComms == "$_Quiz"){$_Quiz;}else if(termComms == "Help"){Help;}else if(termComms == "Quiz"){Quiz;};
int main() {
while(true)
{
std::string termComms;
std::cin >> termComms;
testForInputComm;
return 0;
}
}
int initiation()
{
cout << "Type a command!";
cout << "Type: $_Help to view all of the commands";
return 0;
}
错误信息是:
main.cpp: In function 'int main()':
main.cpp:7:26: error: a function-definition is not allowed here before '{' token
#define $_Quiz int quiz(){int score = 0; std::string name; std::string quest1; cout << "What is your name? "; cin >> name; cout << "Hello, " << name << endl; sc
^
main.cpp:10:91: note: in expansion of macro '$_Quiz'
#define testForInputComm if(termComms == "$_Help"){$_Help;}else if(termComms == "$_Quiz"){$_Quiz;}else if(termComms == "Help"){Help;}else if(termComms == "Quiz"
^
main.cpp:17:10: note: in expansion of macro 'testForInputComm'
testForInputComm;
^
main.cpp:27:1: error: expected '}' at end of input
}
^
main.cpp:27:1: error: expected '}' at end of input
main.cpp:27:1: error: expected '}' at end of input
【问题讨论】:
-
@BenjaminLindley 恐怕实际上是one。
-
只是一个想法,但你的
main呢? -
对不起,我之前的评论很粗鲁。我只是对我所看到的感到震惊。尽管如此,精神依然存在。作为一般规则,如果您可以通过其他任何方式执行此操作,请不要使用宏。
标签: c++ compiler-errors