设置类变量时代码崩溃

Code crashes on setting class variable

本文关键字:崩溃 代码 时代 类变量 设置      更新时间:2023-10-16

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

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 -对象的数目临时-传递整数的临时变量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);
}

经过小测试,我发现它崩溃了,然后代码试图设置"brand"变量。有什么问题吗?

数组尺寸必须在编译时已知,因此:

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
}

除了Lightness的回答,我注意到你的Car类的方法有返回类型,但没有返回语句。运行时错误通常会掩盖大多数编译错误,所以这可能就是为什么它没有引起您的注意。要解决这个问题,用void替换"set"方法的返回值,这意味着该函数不返回任何东西。对所有方法都这样做,因为它们都没有返回语句。

如何不给出任何编译时错误?下面的语句会导致一个错误,因为n在编译时是未知的。你应该将A作为std::vector,或者为"n"使用宏定义或静态const。

    Car A[n];

此外,setter函数不需要任何返回值。它们不返回任何东西,尽管函数签名表明它们应该返回。