我的C ++代码给出了代码中没有的错误。什么是错误?

时间:2016-01-12 13:41:37

标签: c++ oop syntax

当我编译此代码时,它会给出如下所示的运行时错误。但它并没有告诉我的代码中哪一行有问题。

  

调试断言失败!

  程序:C:\ Windows \ system32 \ MSVCP110D.dll
  文件:c:\ program files(x86)\ microsoft visual studio 11.0 \ vc \ include \ xstring
  行:1143

  表达式:无效空指针

  有关程序如何导致断言失败的信息,请参阅有关断言的Visual C ++文档。

  (按“重试”调试应用程序。)

以下是我的C ++代码。包含一个基类:Vehicle和另一个派生类:Car,它是从基类公开继承的。

class Vehicle {

private:
    string VehicleNo, color;

public:
    Vehicle():VehicleNo(NULL),color(NULL){};
    string getVehicleNo(){return VehicleNo;}
    string getColor(){return color;}

    void setVehicleNo(){
        //getline(cin,VehicleNo);
        cin>>VehicleNo;
    }

    void setVehicleColor(){cin>>color;}
};



class Car: public Vehicle {

private:
    int distance;

public:
    void setDistance(int x){distance=x;}
    void setCarNo(){setVehicleNo();}
    void setCarColor(){setVehicleColor();}

    int calculateFare(int x){return 5*x;};


    void displayInformation()
    {
        cout<<"Your Car Number is: "<<getVehicleNo()<<endl;
        cout<<"The color of your Car is: "<<getColor()<<endl;
        cout<<"Total fare which you have to pay: "<<calculateFare(distance);

    }


};

int main()
{
    Car c1;
    int distance;
    char choice;

    cout<<"Enter car number: ";
    c1.setCarNo();

    cout<<"\nEnter Car Color: ";
    c1.setCarColor();

    cout<<"\nHow long would you like to go? Enter distance in kilometers: ";
    cin>>distance;
    c1.setDistance(distance);

    cout<<"\n----------------------------------\n";
    c1.displayInformation();
    cout<<"\n----------------------------------\n";

    cout<<"\nDo you want to calculate Fare of different distance (y/Y for yes and another character for No?  ";
    cin>>choice;

    do{

        cout<<"\nHow long would you like to go? Enter distance in Kilometers: ";
        cin>>distance;
        cout<<"\n----------------------------------\n";
        c1.setDistance(distance);

        c1.displayInformation();

        cout<<"\nDo you want to calculate Fare of different distance (y/Y for yes and another character for No?  ";
        cin>>choice;
    } 
    while(choice=='y' || choice=='Y');
}

2 个答案:

答案 0 :(得分:3)

C ++提供了9个string构造函数:http://en.cppreference.com/w/cpp/string/basic_string/basic_string

其中两个接受指针:

  1. basic_string(const CharT* s, size_type count, const Allocator& alloc = Allocator())
  2. basic_string(const CharT* s, const Allocator& alloc = Allocator())
  3. 当你调用VehicleNo(NULL)color(NULL)时,你只是将空指针而不是count传递给string构造函数,因此编译器将你的null参数传递给option <强> 2 即可。 s预计在哪里:

      

    指向字符串的指针,该字符串用作使用

    初始化字符串的源

    string构造函数尝试取消引用s以将其内容复制到正在构建的string时,会发生段错误。

    您在此处尝试构建的内容为空string。当您使用默认构造函数时,C ++已经这样做了:string()

    如果构造函数初始化列表中未指定构造,则将调用成员对象的默认构造函数。因此,您不需要在构造函数初始化列表中放置VehicleNocolor来将它们构造为空string。这意味着你可以使用编译器生成的默认构造函数,并一起摆脱你的构造函数。

答案 1 :(得分:-1)

您的问题是这行代码

Vehicle():VehicleNo(NULL),color(NULL){};

VehicleNO和颜色是字符串类型。它们不能为NULL。把它改成这样的东西

Vehicle() :VehicleNo(" "), color(" "){};