当我编译此代码时,它会给出如下所示的运行时错误。但它并没有告诉我的代码中哪一行有问题。
调试断言失败!
程序: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');
}
答案 0 :(得分:3)
C ++提供了9个string
构造函数:http://en.cppreference.com/w/cpp/string/basic_string/basic_string
其中两个接受指针:
basic_string(const CharT* s, size_type count, const Allocator& alloc = Allocator())
basic_string(const CharT* s, const Allocator& alloc = Allocator())
当你调用VehicleNo(NULL)
和color(NULL)
时,你只是将空指针而不是count
传递给string
构造函数,因此编译器将你的null参数传递给option <强> 2 即可。 s
预计在哪里:
指向字符串的指针,该字符串用作使用
初始化字符串的源
当string
构造函数尝试取消引用s
以将其内容复制到正在构建的string
时,会发生段错误。
您在此处尝试构建的内容为空string
。当您使用默认构造函数时,C ++已经这样做了:string()
。
如果构造函数初始化列表中未指定构造,则将调用成员对象的默认构造函数。因此,您不需要在构造函数初始化列表中放置VehicleNo
或color
来将它们构造为空string
。这意味着你可以使用编译器生成的默认构造函数,并一起摆脱你的构造函数。
答案 1 :(得分:-1)
您的问题是这行代码
Vehicle():VehicleNo(NULL),color(NULL){};
VehicleNO和颜色是字符串类型。它们不能为NULL。把它改成这样的东西
Vehicle() :VehicleNo(" "), color(" "){};