jsp*_*p99 0 c++ enums runtime-error class
写此代码之前我的目标是只是练习和学习更多关于C++.
该代码由一个类球组成,该球具有球的属性,如颜色,大小,重量以及球的"品牌"和价格.
#include<iostream>
#include<string>
using namespace std;
class ball
{
private:
int price; //Price of a ball in rupees .
enum colour { red , green , blue } colour; // Colour of the ball .
string brand; // Brand of the ball REEBOK ADIDAS etcetera .
float size; // Diameter of the ball .
enum weight { light , medium , heavy }weight; // Qualitative weight .
public:
ball();
void get_price();
void get_colour();
void get_brand();
void get_size();
void get_weight();
};
ball::ball() : price(0) , brand(NULL) , size(0.0)
{
cout<<"In the constructor";
colour=blue;
weight=medium;
}
void ball::get_price()
{
cout<<"In the function get_price()"<<endl<<price<<endl;
}
void ball::get_colour()
{
cout<<"In the function get_colour()"<<endl<<colour<<endl;
}
void ball::get_brand()
{
cout<<"In the function get_brand()"<<endl<<brand<<endl;
}
void ball::get_size()
{
cout<<"In the function get_size()"<<endl<<size<<endl;
}
void ball::get_weight()
{
cout<<"In the function get_weight()"<<endl<<weight<<endl;
}
int main()
{
ball glace;
glace.get_price();
glace.get_colour();
glace.get_brand();
glace.get_size();
glace.get_weight();
}
Run Code Online (Sandbox Code Playgroud)
问题出现在类定义中使用枚举.最初我遇到了像C2436,C2275,C2064这样的错误.每次编译时的所有错误都归因于枚举.修复它们之后,最后上面的代码编译没有错误!但它给了我一个运行时错误.!
任何人都可以向我解释原因吗?
PS:我使用的是Microsoft Visual C++ 2005快递版.
你在std :: string上调用brand(NULL),这就是你得到的运行时错误.它调用std :: string构造函数,它接受一个char const*,从C字符串创建,它不能为NULL.要构造一个空的std :: string,只需在初始化列表中调用brand(),或者甚至跳过它,因为如果你这样做,编译器会自动调用默认构造函数.