当我编译此代码时,它会给出如下所示的运行时错误 . 但它并没有告诉我的代码中哪一行有问题 .
调试断言失败!程序: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 回答
C提供了9个
string
构造函数:http://en.cppreference.com/w/cpp/string/basic_string/basic_string其中2个接受指针:
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参数传递给选项 2 .s
预计在哪里:当
string
构造函数尝试取消引用s
将其内容复制到正在构造的string
时,它会发生段错误 .你在这里想要构建的是一个空的
string
. 当你使用默认构造函数时,C已经这样做了:string()
.成员对象's default constructor will be called if no construction is specified in the constructor intialization list. So you won't需要在构造函数初始化列表中放置
VehicleNo
或color
以将它们构造为空string
. 这意味着你可以使用编译器生成的默认构造函数,并一起摆脱你的构造函数 .你的问题是这行代码
VehicleNO和颜色是字符串类型 . 它们不能为NULL . 把它改成这样的东西