我是C++新手,并试图实现一些方法。
我创建了一个智能指针类 CarPtr,如下所示:
template <class Car>
class CarPtr
{
public:
Car *ptr; // Actual pointer
// Constructor
explicit CarPtr(Car *p = nullptr) { ptr = p; }
// Destructor
~CarPtr() { delete(ptr); cout << "CarPtr destructor" << endl;}
// Overloading dereferencing operator
Car &operator *() { return *ptr; }
Car *operator -> () { return ptr; }
};
#endif /* CARPTR_H_ */
然后,我创建了 Car 类的一个实例,并使用我的智能指针指向它。
CarPtr<Car> carInfoCreation()
{
CarPtr<Car> p(new Car());
int carId;
int carYear;
double carCost;
String carMake;
String carModel;
cout << "please enter the Id for the car" << endl;
cin >> carId;
p.ptr->setId(carId);
cout << "please enter the Year for the car" << endl;
cin >> carYear;
p.ptr->setYear(carYear);
cout << "please enter the Cost for the car" << endl;
cin >> carCost;
p.ptr->setCost(carCost);
cout << "please enter the Make for the car" << endl;
cin >> carMake;
p.ptr->setMake(carMake);
String getMake = p.ptr->getMake();
cout << "please enter the Model for the car" << endl;
cin >> carModel;
p.ptr->setModel(carModel);
String getModel = p.ptr->getModel();
cout << "Car Info: " << endl;
cout << "Car Id: "<< p.ptr->getId() << endl;
cout << "Car Year: "<< p.ptr->getYear() << endl;
cout << "Car Cost: " << p.ptr->getCost() << endl;
cout << "Car Make: " << getMake << endl;
cout << "Car Model: " << getModel << endl;
ofstream myfile;
myfile.open ("Car 1.txt");
myfile << "Car Id: " << carId << endl;
myfile << "Car Year: " << carYear << endl;
myfile << "Car Cost: " << carCost << endl;
myfile << "Car Make: " << carMake << endl;
myfile << "Car Model: " << carModel << endl;
myfile.close();
return p;
}
创建实例后,我希望返回智能指针 p 并将其放入我创建的智能指针数组中,如下所示:
CarPtr<Car> CarPtrArray[5];
CarPtrArray[0] = carInfoCreation() ;
运行代码后,实例创建成功,可以看到对应的.txt文件。但紧接着,我会看到 Eclipse 显示的错误:
"XXX.exe已停止工作
问题导致程序停止正常工作。Windows将关闭程序,并在解决方案可用时通知您。
谁能帮我解决这个问题?如果您需要更多代码或相关信息,请告诉我。
谢谢!
你的类需要遵循三/五/零的规则。
如果没有它,像你一样按值返回一个会导致未定义的行为:当临时返回对象被销毁(和/或本地对象被返回(时,指针将被删除,但随后调用代码继续使用指针。