对于已经声明的engine显示未声明,并且竟然Engine类也显示未声明,很困惑。
注意delete和new的对应 这个报错我还真没看出来问题,除非把你代码贴出来调一下
我简单试了一下是没啥问题的
#include <iostream>
#include <string>
using namespace std;
#include <stdio.h>
class Engine {
private:
string* engine;
public:
~Engine();
Engine(string engine_);
void printstr()
{
printf("%s \n", engine->c_str());
};
};
Engine::~Engine()
{
delete engine;
}
Engine::Engine(string engine_)
{
engine = new string(engine_);
}
int main()
{
Engine ll("123");
ll.printstr();
string* str;
string str1 = "123";
str = new string(str1);
printf("%s \n", str->c_str());
delete str;
return 0;
}
你这里engine是一个string指针,在析构函数里为啥用delete[],这个是对数组用的,在拷贝构造里*el->engine又是啥。C++对这种情况用智能指针不好吗
#include"Engine.h"
#include
using std::string;
class Truck {
private:
string* truckType = nullptr;
Engine* engineType = nullptr; //提供 Engine 类型的成员对象
public:
Truck(string truckType_, string engineType_);//接受字符串类型参数的构造函数
Truck(const Truck& t); //拷贝构造函数
string getTrucktype();
string getengineType_();
~Truck();
};
Truck::Truck(string truckType_, string engineType_) {
truckType = new string(truckType_); // 为指针分配内存并拷贝值
engineType->setengineType(engineType_); //调用setter函数
}
Truck::Truck(const Truck& t) {
truckType = new string(*t.truckType); //为指针分配内存并拷贝值
}
string Truck::getTrucktype() {
return *truckType;
}
string Truck::getengineType_() {
return *engineType->getengineType();
}
Truck::~Truck() { delete[] truckType; delete[] engineType; }//释放内存