c++ - 枚举和类 - 运行时错误!!

标签 c++ class enums runtime-error

在编写这段代码之前,我的目标是只是练习和学习更多关于 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 Edition。

最佳答案

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

关于c++ - 枚举和类 - 运行时错误!!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7376452/

相关文章:

带有二维数组的 C++ 宏

C++ 如何将 Vector 的两个对象合并、合并、相交到新的第三个对象中?

java - 当创建一个类来保存变量时,变量应该始终是静态的吗?

c# - 从字符串中获取枚举字段

c++ - 如何使用 C++ 从图像采集卡中获取图像?

c++ 两点赋值之间的距离

c++ - 将 vector 与对象一起使用错误

python - 在python中创建字典的字典

c++ - 虚函数返回的枚举协方差

c# - 在 C# 中将整数转换为枚举