我有两个这样的类:
foo.h
class A //base class
{
public:
A(QList<int> &timers, QList<int> &positions);
int pIndex = 0;
QList<int> timers;
QList<int> positions;
};
class B : public A
{
public:
B();
private:
QList<int> t { 5, 8, 10, 20, 25 };
QList<int> p { 10, 15, 20 };
};
foo.cpp
B::B()
: A(t, p)
{
}
A::A(QList<int> &t, QList<int> &p)
{
foreach (int v, t) {
qDebug() << "v = " << v;
}
//this->timers = t;
//this->positions = p;
}
但是当我初始化 B 类时,它崩溃并提示 SGIFAULT。
auto b = new B();
出现此错误我错过了什么?起初我以为是我传递的 QList 有时变成了垃圾内存但是这段代码遵循相同的原则但使用了 int[]
相反 QList<int>
确实工作正常:
class A
{
public:
A(int p[3])
{
this->v = p;
}
void print()
{
for(int i = 0; i < 3; ++i)
{
printf("v = %d\n", v[i]);
}
}
private:
int *v = NULL;
};
class B : public A
{
public:
B() : A(values)
{
}
private:
int values[3] = {1, 2, 3};
};
int main() {
A *o = new B();
o->print();
}
最佳答案
问题是,当你调用基类构造函数时,t
和 p
还没有构造:
检查一下(static
成员是在创建任何类对象之前构造的,请注意这可能不是您正在寻找的解决方案):
class B : public A
{
public:
B();
private:
static QList<int> t;
static QList<int> p;
};
QList<int> B::t { 5, 8, 10, 20, 25 };
QList<int> B::p { 10, 15, 20 };
现在编译输出
5
8
10
20
25
此外,您没有将第二个 QList
传递给基类构造函数。
替代版本:
class A
{
public:
//const references
A(const QList<int> &timers, const QList<int> &positions);
int pIndex = 0;
QList<int> timers;
QList<int> positions;
};
class B : public A
{
public:
B();
private:
// no need for QList members
};
B::B()
: A({ 5, 8, 10, 20, 25 }, { 10, 15, 20 }) // use initializer lists directly
{
}
A::A(const QList<int> &t, const QList<int> &p)
{
for (int v : t) {
qDebug() << "v = " << v;
}
}
int main()
{
auto b = new B();
delete b;
}
关于c++ - 这个列表是垃圾内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555927/