Enums and classes - Run time error !!
My aim before writing this code was to just practice and learn more about C++ .
The code consists of a class ball which has a ball's properties like colour , size , weight and also the 'brand' and price of the ball .
#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();
};
开发者_如何学C
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();
}
The problem came with the usage of enums in class definition . Initially I got errors like C2436 , C2275 , C2064 . All the errors at each compilation were due to the enum . After fixing them , finally the above code is compilation error free ! But it's giving me a run-time error . !!
Can anyone explain it to me why ?
PS : I use Microsoft Visual C++ 2005 express edition .
You call brand(NULL) on a std::string, that's the runtime error you are getting. It's calling the std::string constructor that takes a char const*, to create from a C string, and it can't be NULL. To construct an empty std::string simply call brand() in your initialization list, or even skip it since if you do the default constructor would be called automatically by the compiler.
精彩评论