gpt4 book ai didi

c++ - 无法在 C++ 中构建复杂结构

转载 作者:行者123 更新时间:2023-11-28 08:31:08 25 4
gpt4 key购买 nike

我有两个基本结构如下:

struct stuSectionProperties
{

int Field1; // Row | BoxNo | SplitterNo
int Field2; // Col | Adapter | -
double Latitude;
bool IsEast;
int Band;
int CableNo;
SDP::Global::enuSections::Type Section;

stuSectionProperties()
{
this->Field1 = -1;
this->Field2 = -1;
this->Latitude = -1;
this->Band = -1;
this->Section = SDP::Global::enuSections::None;
this->CableNo = -1;
}
const char* toStr()
{
return ((QString) (QString::number(this->Field1) + " , " + QString::number(this->Field2) + " , " + QString::number(Latitude) + " , " + QString::number(IsEast) + " , " + QString::number(Band) + " , "
+ QString::number((int) Section) + QString::number((int) CableNo))).toStdString().c_str();
}
};

struct stuSearchResult
{
stuSectionProperties MyData;
QList<stuSectionProperties> Connections;

stuSearchResult()
{
this->MyData.Field1 = -1;
this->MyData.Field2 = -1;
this->MyData.Latitude = -1;
this->MyData.Band = -1;
this->MyData.Section = SDP::Global::enuSections::None;
this->MyData.CableNo = -1;

stuSectionProperties stuDummy;
stuDummy.Band=-1;
stuDummy.CableNo=-1;
stuDummy.Field1=-1;
stuDummy.Field2=-1;
stuDummy.IsEast=-1;
stuDummy.Latitude=-1;

stuDummy.Section= SDP::Global::enuSections::None;
this->Connections.append(stuDummy);

}
const char * toStr()
{
return ((QString) (QString::number(this->MyData.Field1) + " , " + QString::number(this->MyData.Field2) + " , " + QString::number(this->MyData.Latitude) + " , " + QString::number(this->MyData.IsEast) + " , " + QString::number(this->MyData.Band) + " , "
+ QString::number((int) this->MyData.Section) + QString::number((int) this->MyData.CableNo)) + " , " + QString::number(this->Connections[0].Field1) + " , " + QString::number(this->Connections[0].Field2) ).toStdString().c_str();
}
};

每当我尝试从第二个结构中创建一个实例,然后尝试调用它的 toStr() 成员时,我都会得到一个错误,表明这些行有一些问题:

+ QString::number(this->Connections[0].Field1) + " , " + QString::number(this->Connections[0].Field2)

你能告诉我我的问题到底是什么吗?问候。

最佳答案

断言错误表明 Connections 没有您引用的元素。如果你打印出 Connections.size() 它表示列表包含多少个元素?

返回 string.c_str() 可能是一个潜在的内存问题,因为它返回指向已释放内存的指针。

在 C++ 中,自定义打印通常是通过在类中重载流运算符来完成的:

friend std::ostream &operator<<(std::ostream &os, const myClass &c)
{
return os << c.some << c.val;
}

...

cout << myObj << endl;

...

strstream ss;
ss << "cool: " << myObj << " " << 55;
string s = ss.str();

您还可以在 toStr 函数中传递对字符串对象的引用:

makeString(string &s)
{
...
s = qstr.toStdString();
}

string s;
makeString(s);

关于c++ - 无法在 C++ 中构建复杂结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2018718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com