【问题标题】:Enums and classes - Run time error !!枚举和类 - 运行时错误!
【发布时间】:2011-09-11 05:21:15
【问题描述】:

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

问题来自于在类定义中使用 enums。 最初我遇到了 C2436 、 C2275 、 C2064 之类的错误。 每次编译时的所有错误都是由于枚举引起的。修复它们之后,上面的代码终于编译错误了!但它给了我一个运行时错误。 !!

谁能给我解释一下为什么?

PS:我用的是Microsoft Visual C++ 2005 express edition。

【问题讨论】:

  • 显示发送错误报告的对话框

标签: c++ class enums runtime-error


【解决方案1】:

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

【讨论】:

  • 不,我没这么说。我没有检查你的枚举代码,只是寻找你的运行时错误的来源。
  • 因为 enums 我得到了很多编译时错误。所以认为即使是这个运行时错误也可能是因为它们。感谢您的澄清。 :)
  • 现在等到您看到输出流式枚举枚举打印出一个整数,而不是一个名称。顺便说一句,这些函数没有得到任何东西,因此您可能需要考虑将它们重命名为 print_to_cout_* 或类似名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多