设置类变量时代码崩溃
Code crashes on setting class variable
我刚刚写了一个小的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函数不需要任何返回值。它们不返回任何东西,尽管函数签名表明它们应该返回。
相关文章:
- 为什么所有C++编译器都会崩溃或挂起此代码
- 使用 g++7 构建的代码在访问未对齐的内存时崩溃
- 您好,我实际上想了解以下代码.有人可以详细说明代码它到底在做什么吗?为什么它会在第 31 行崩溃
- 无法访问的代码如何导致我的程序崩溃?
- C++代码崩溃并具有无限循环
- 由于指针算法错误,代码在 memcpy 中崩溃
- 为什么在同一条件变量上使用多个互斥锁会使此代码崩溃?
- 运行简单的.oct文件时Octave崩溃,我的代码出了什么问题?
- 为什么代码会崩溃?(在CPP中)
- 赋值运算符在我制作类模板时使代码崩溃
- 为什么抓取窗口标题的代码会导致应用崩溃?
- 类似的代码.一个工作,一个崩溃.为什么?
- 为什么这段代码崩溃了
- 为什么此代码在此 Trie 实现中使用映射 c++ 中的指针崩溃?
- 为什么此代码会崩溃?(我是C 的新手)
- 程序过早结束,可能已经崩溃了.退出代码0xc0000005
- C++ - 代码在Visual Studio中完美运行,但命令行中的.exe不断崩溃
- 如何在导致应用程序崩溃的代码中修复指令
- 运行时,程序崩溃(代码块C++)
- 是我的编译器将适当的代码优化为无用的崩溃代码