我有一个这样声明的结构:
struct sExample {
int something;
char somethingElse[32];
bool another;
// many other fields
};
它有更多的int
、char[]
和bool
。现在让我们面对这个问题。首先,我创建了一个使用 sExample
类型的临时变量的类。
class ExClass {
void fun() {
sExample myStruct;
// Initialize some of the struct fields (just some of them!)
strcpy(myStruct.somethingElse, "TEXT");
// Use struct in function that may read or modify it
globalFunction(&myStruct);
}
}
它工作得很好,但后来我决定 myStruct
应该比函数 fun 中的可用时间更长,所以我将它移至类成员:
class ExClass {
sExample myStruct;
void fun() {
// Same code as above
// Initialize some of the struct fields (just some of them!)
strcpy(myStruct.somethingElse, "TEXT");
// Use struct in function that may read or modify it
globalFunction(&myStruct);
}
}
问题就在这里。调用 globalFunction
会导致段错误(这是来自外部第 3 方库的函数,因此我无法确定问题到底出在哪里)。
我还尝试使用 = {0}
初始化结构,但没有帮助。有什么问题吗?
我正在使用 Gcc 4.9、C++11。
谁能解释一下这里有什么问题吗?
最佳答案
如果这是您唯一的更改,那么您的问题是您在 ExClass
的无效实例上调用 fun()
。或者您忘记新建该类,或者它已被删除/超出范围。
F.e.这个Ideone示例工作完美,因为 A a
是在 fun()
内部的堆栈上创建的。但是,一旦将 a
的声明移至类级别,您将收到异常,因为 *b
未实例化。
#include <iostream>
using namespace std;
struct A {
int data;
A() : data(123) { }
};
class B {
public:
void fun() {
A a;
cout << a.data;
}
};
int main() {
B* b; // b points to random memory, thus is an invalid instance
b->fun(); // this still works because fun doesn't access any member of B
return 0;
}
关于c++ - 结构体创建问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185408/