gpt4 book ai didi

c++ - 代码在设置类变量时崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:36 25 4
gpt4 key购买 nike

我只是在写一个小的 OOP 应用程序并在运行(不是编译)应用程序时崩溃通过 setter 设置类的私有(private)字符串变量,这是头文件:

class Car
{
private:
int year;
std::string brand;
std::string model;
int price;
std::string currency;
public:
int setYear(int x){this->year = x;}
std::string setBrand(std::string x){this->brand = x;}
std::string setModel(std::string x){this->model = x;}
int setPrice(int x){this->price = x;};
std::string setCurrency(std::string x){this->currency = x;}
};

这里是主要的:n - 对象数temp - 用于传递整数的临时变量temp1 - 用于传递字符串的临时变量

ifstream fd("input.in");
int n;
fd >> n;
int temp;
string temp1;
Car A[n];
for(int i = 0; i < 3; i++)
{
fd >> temp;
A[i].setYear(temp);
fd >> temp1;
A[i].setBrand(temp1); //Crashes Here
fd >> temp1;
A[i].setModel(temp1);
fd >> temp;
A[i].setPrice(temp);
fd >> temp1;
A[i].setCurrency(temp1);
}

经过少量测试后,我发现它崩溃了,然后代码尝试设置“品牌”变量。有什么问题?

最佳答案

数组维度必须在编译时已知,所以:

C A[n];

错了。

GCC 支持可变长度数组作为非标准扩展,但是,即使您不小心使用了它们,您的循环也会假定 n == 3,但没有明显迹象表明这一定是真的。

相反,使用 vector :

std::vector<C> A(n);

并正确地迭代它:

std::vector<C>::iterator it = A.begin(), end = A.end();
for ( ; it != end; ++it) {
// your for loop stuff with *it
}

或者,在 C++11 中:

for (auto& a : A) {
// your for loop stuff with a
}

关于c++ - 代码在设置类变量时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14102964/

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