2011-09-11 102 views
0

我在编写这段代码之前的目标是到只是练习和了解更多关于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(); 
} 

问题来了的类定义枚举使用。 最初我遇到了像C2436,C2275,C2064这样的错误。 每个编译中的所有错误均归因于枚举。修复后,最后上面的代码是编译错误免费!但它给我一个运行时错误。 !

任何人都可以向我解释为什么? PS:我使用Microsoft Visual C++ 2005 express版本。

+0

哪个运行时错误?哪里? –

+0

那个说**的对话框发送错误报告** – jsp99

回答

5

您在std :: string上调用品牌(NULL),这就是您所得到的运行时错误。它调用std :: string构造函数,它使用一个char const *来从C字符串创建,并且它不能为NULL。要构造一个空的std :: string,只需在你的初始化列表中调用brand(),或者甚至跳过它,因为如果你这样做了,默认的构造函数会被编译器自动调用。

+0

THANKs :) ..所以,你说我的枚举没有错? – jsp99

+0

不,我不这么说。我没有检查你的枚举代码,只是寻找你的运行时错误的来源。 –

+0

由于枚举,我得到了许多编译时错误。所以认为即使这个运行时间错误可能是因为他们。谢谢澄清。 :) – jsp99