list<Text*> textList; //global declaration of textList
void addText(int w, int h){
Text *text = new Text; //error in this line
text->init(w,h);
textList.push_back(text);
}
void printText(){
for(list<Text*>::iterator it = textList.begin(); it != textList.end(); ++it)
{
(*it)->print();
}
}
我创建了一个全局 textList
指针的 Text
类。 addText()
& printText()
从另一个类 (c++) 调用。但是在创建文本对象时出错
我是否可以全局使用 textList
并在函数中本地向其添加对象
最佳答案
如果您在Text *text = new Text;
行中遇到错误,那是因为您没有匹配的构造函数来构建Text
没有参数。
因为如果您调用了正确的构造函数,通常您的代码应该可以正常工作。
因此,回答您的问题,是的可以像您一样使用textList
。您遇到的错误与该全局变量无关。
关于c++ - 全局列出对象并在 c/c++ 中添加类的本地对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24904432/