在一个作业项目中,我需要使用一个对象,并且它的初始化由if条件控制,所以看起来有点复杂,因此我想将初始化过程作为一个函数。但是我可以在函数内初始化这个对象然后在外面使用吗?
以下是代码段:
void playOneGame(Lexicon& dictionary) {
// TODO: implement
setConsoleClearEnabled(true);
// initialize object: if yes, generate it randomly, else by human input
if (getYesOrNo("Do you want to generate a random board?")) {
// generate boggle randomly by using constructor
Boggle myBoggle(dictionary, "");
} else {
string boardText = getLine("Type the 16 letters to appear on the board:");
//boardText = stripText(boardText);
while (boardText.length() != 16 || containsNonAlpha(boardText)) {
cout << "That is not a valid 16-letter board string. Try again." << endl;
boardText = getLine("Type the 16 letters to appear on the board:");
}
}
答案 0 :(得分:1)
void playOneGame(Lexicon& dictionary) {
// TODO: implement
setConsoleClearEnabled(true);
Boggle myBoggle = setupBoard(dictionary);
}
Boggle setupBoard (Lexicon& dictionary) {
if (getYesOrNo("Do you want to generate a random board?")) {
Boggle myBoggle(dictionary, "");
return myBoggle;
} else {
string boardText = getLine("Type the 16 letters to appear on the board:");
//boardText = stripText(boardText);
while (boardText.length() != 16 || containsNonAlpha(boardText)) {
cout << "That is not a valid 16-letter board string. Try again." << endl;
boardText = getLine("Type the 16 letters to appear on the board:");
}
Boggle myBoggle(dictionary, boardText);
return myBoggle;
}
}
这是解决方案