我的C++代码给出了代码中没有的错误.虫子是什么

My C++ code gives error which is not seen in code. Whats the bug?

本文关键字:代码 错误 是什么 C++ 我的      更新时间:2023-10-16

编译此代码时,会出现如下所示的运行时错误。但它并不能说明我的代码中哪一行有错误。

调试断言失败

程序: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');
}

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

其中2个接受指针:

  1. basic_string(const CharT* s, size_type count, const Allocator& alloc = Allocator())
  2. basic_string(const CharT* s, const Allocator& alloc = Allocator())

当您调用VehicleNo(NULL)color(NULL)时,您只向string构造函数传递了一个空指针,而不是count,因此编译器会将您的空参数传递到选项2中。s的预期位置:

指向字符串的指针,用作用初始化字符串的源

string构造函数试图取消引用s以将其内容复制到正在构造的string中时,它会分段故障。

您试图在这里构建的是一个空的string。当您使用默认构造函数string()时,C++已经做到了这一点。

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

您的问题是的这行代码

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

VehicleNO和颜色属于字符串类型。它们不能为NULL。将其更改为类似的内容

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