struct数组的Vector将字符串重置为空白.c++



所以我有一个非常令人困惑的问题,我试图从结构体数组的向量打印一个字符串到控制台。整数打印很好,但是存储在这些结构体中的字符串被设置为";我不知道这里发生了什么,但在设置了如下所示的测试后,这个问题仍然存在。如果能帮我解决这个问题,我将不胜感激。

还应该提到我仍然是c++的新手,所以如果这里的问题是一些简单的事情,我很抱歉。

#include <iostream>
#include <string>
#include <vector>
#include "Header.h"
//Test struct
struct testStruct
{
string testString;
int testInt;
};
testStruct testArray[1] = {
testArray[0] = {"String works", 69}
};
int main()
{
srand(time(NULL));

vector < testStruct > test;
test.push_back({ testArray[0] });
cout << test[0].testString << "n"; // prints "", should print "String works"
cout << test[0].testInt << "n"; // prints 69

characterCreation();
checkPlayerStats();
introduction();
return 0;
}

这让我很惊讶。以下代码是合法的(至少在语法上)

testStruct testArray[1] = {
testArray[0] = {"String works", 69}
};

但是如果你将它替换为合理的版本

testStruct testArray[1] = {
{"String works", 69}
};

那么你的程序就能正常工作。

我希望你的版本有未定义行为,因为你正在分配(这里是testArray[0] = ...)给一个尚未创建的数组元素。

testStruct testArray[1] = {

定义了这个数组。然后,构造这个数组。在什么时候,这个数组被构造,对于这个问题来说是无关紧要的。只要注意到{ ... }中的内容被求值并用于构造该数组就足够了。

testArray[0] = {"String works", 69}

该表达式构造数组的第一个值。这个表达式赋值给testArray[0]

问题是testArray[0]还没有构建,这就是现在正在发生的事情。这是未定义的行为。就像先有鸡还是先有蛋一样。

你在程序的结果中看到了未定义行为的结果。程序的结果可以是任何东西,而这恰好是在尘埃落定之前,由于编译器和c++库在可执行代码方面碰巧产生的结果。

所以首先你需要使用std::vectorstd::cout,因为你还没有使用using namespace std

但你的主要问题是:

testStruct testArray[1] = {
testArray[0] = {"String works", 69}
};

首先,它不应该是全局的,因为它不需要。

第二,这是不正确的:

testArray[0] = {"String works", 69}

你不应该在数组中这样做。你可能想要做的是:

testStruct testArray[1] = {{"String works", 69}}; // uses aggragate initialization.

那么现在这将有正确的输出,使用以下程序:

#include <iostream>
#include <string>
#include <vector>
#include "Header.h"
//Test struct
struct testStruct
{
string testString;
int testInt;
};
int main()
{
testStruct testArray[1] = {{"String works", 69}};
srand(time(NULL));

vector < testStruct > test;
test.push_back({ testArray[0] });
cout << test[0].testString << "n"; // prints "String works".
cout << test[0].testInt << "n"; // prints 69.

characterCreation();
checkPlayerStats();
introduction();
return 0;
}

假设您有Header.h头文件

最新更新