它只运行main,输出"输入一个单词"但完全忽略了对象/类
我是个新手,对不起,如果这是一个不恰当的简单问题。 这在发布和调试模式下都会发生
#include <iostream>
using namespace std;
class WordGame
{
public:
void setWord( string word )
{
theWord = word;
}
string getWord()
{
return theWord;
}
void displayWord()
{
cout << "Your word is " << getWord() << endl;
}
private:
string theWord;
};
int main()
{
cout << "Enter a word" << endl;
string aWord;
WordGame theGame;
cin >> aWord;
theGame.setWord(aWord);
theGame.displayWord();
}
答案 0 :(得分:4)
您需要输入一个单词,然后按Enter键。你说“它退出程序,没有任何反应”,但确实发生了一些事情。它发生得太快你可能会看到它发生并且程序关闭。如果您处于调试模式并想要“按键退出消息”,请执行
system("PAUSE");
后
theGame.displayWord();
您将看到cout
显示。
此外,您的代码存在一些优化和错误。
main
的返回值。setWord
,您应该通过const引用,因此函数将是。 void setWord( const string& word )
getWord
,您应该通过const引用返回,因此函数将是 string getWord()
有关传递const引用的更多信息,请查看Passing arguments by reference。
答案 1 :(得分:2)
在Visual Studio中,如果右键单击项目,然后转到Properties-&gt; Linker-&gt; System-&gt; SubSystem,您可以将其设置为Console,这样它就不会立即退出并阻止您不得不使用系统( “暂停”)。系统(“暂停”)是Windows的东西并且阻止了可移植性。
答案 2 :(得分:0)
其他答案已经建议更改IDE属性以防止控制台立即退出,或使用系统(“PAUSE”);您也可以简单地加载自己的控制台,并从那里手动运行可执行文件(既不是IDE也不依赖于平台)。
但是,最终,您不知道您的用户将使用什么环境或者他们将如何加载程序,因此更合适的解决方案是自己实施某些功能,以防止程序退出,直到您确定用户已完成读取输出。例如:
WordGame theGame;
bool exit = false
while (!exit)
{
cout << "Enter a word. Entering \"exit\" will terminate the program." << endl;
string aWord;
cin >> aWord;
if (aWord == "exit") exit = true;
else
{
theGame.setWord(aWord);
theGame.displayWord();
}
}