是否有一种方法可以在函数内部初始化对象,然后在函数外部使用它
is there a way to initialize an object inside of a function and then use it outside the function?
在一个作业项目中,我需要使用一个对象,它的初始化由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;
}
}
解决方案
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 有没有办法将重载的类函数绑定到函数对象?
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 如何通过接口将函子分配给函数对象
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- 指向std::invoke中成员函数对象的指针
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- "std::function"的简单版本:函数对象的生存期?
- C++ 将函数对象作为左值和/或右值传递
- SFINAE 用于具有默认参数的函数对象
- 构造函数对象赋值是否泄漏内存
- 如何发送通过绑定到函数/方法创建的函数对象?
- std::for_each 与函数对象
- 将函数对象传递给 std::function
- 访问执行策略for_each函数对象中的迭代器
- 通过C++函数对象类访问参数