首先,我是 C++ 新手。如果有更好的方法来做到这一点,那么结构,请提及。
所以我想做的是创建一个结构来存储指向某些自定义对象的指针。这样做的原因是不必传递许多参数指针,我可以声明这个结构并将该结构传递给需要这组对象的函数。
所有对象的原因是我正在与 Web 服务进行交互。我创建了一个类来简化与 Web 服务的交互,并且不希望每次需要时都销毁并重新创建它们。
注意:这是在 Qt 5 中完成的
这是在标题中:
struct MyStruct
{
MyClass* Class1;
MyClass* Class2;
MyClass* Class3;
MyClass* Class4;
};
现在这是我尝试填充结构的片段:
//Stucture of commonly used objects, for all to access
MyStruct* theStruct;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//Build object
MyClass* firstClass = new MyClass(/*params for object*/);
theStruct->Class1 = firstClass;
ui->setupUi(this);
connect(firstclass, SIGNAL(dataReady()),this,SLOT(updateWebStats(MyStruct)));
}
现在我得到的错误是:
应用输出:
Starting MyExe.exe Error - RtlWerpReportException failed with status code :-1073741823. Will try to
直接启动进程:
The program has unexpectedly finished. MyExe.exe crashed
当我调试时,我得到一个弹出窗口
The inferior stopped because it received a signal from the Operating System.
Signal name : SIGSEGV
Signal meaning : Segmentation fault
此时调试器在这一行,在主窗口构造函数中:
theStruct->Class1 = firstClass;
最佳答案
我不同意使用全局变量让生活更轻松的想法。 Are global variables bad?
但这是你的错误。
theStruct
,也必须初始化。
如果它是一个静态成员,你应该将它设置为零。
将类的指针也设置为零也是一种很好的做法。
struct theStruct
{
// default constructor
theStruct() : Class1(0), Class2(0), Class3(0), Class4(0) {}
MyClass* Class1;
MyClass* Class2;
MyClass* Class3;
MyClass* Class4;
};
然后在访问时,您应该检查以确保它已初始化:
if(theStruct && theStruct->Class1)
theStruct->Class1->foo();
上述 if 语句的顺序执行以下操作:如果 theStruct 不为零,也就是调用了 new
并且是一个有效指针,并且如果 theStruct 中的 Class1 不为零(也有new
调用它),然后使用它,因为它是安全和可用的。
希望对您有所帮助。
关于C++ 不能在结构中存储指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26435233/