是否有一种方法可以在函数内部初始化对象,然后在函数外部使用它

is there a way to initialize an object inside of a function and then use it outside the function?

本文关键字:函数 对象 初始化 然后 外部 内部 一种 方法 是否      更新时间:2023-10-16

在一个作业项目中,我需要使用一个对象,它的初始化由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:");
    }  
}
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;
}

}

解决方案