【发布时间】:2020-07-29 17:45:08
【问题描述】:
Upd:很抱歉,如果我用这样的问题打扰别人。我今年 48 岁。我正在努力寻找新的职业。我只需要“做这个”之外的更多信息。不要那样做。永远不要问为什么。 :) 感谢大家对我善良的人的回答和耐心:)
我有Class Car。
class Car {
protected:
std::string Name;
short Year;
float Engine;
float Price;
public:
Car() {
Name = "ordinary";
Year = 1980;
Engine = 2.0;
Price = 1000.;
}
Car(std::string name, short year, float engine, float price) {
Name = name;
Year = year;
Engine = engine;
Price = price;
}
Car(Car& other) {
this->Name = other.Name;
this->Year = other.Year;
this->Engine = other.Engine;
this->Price = other.Price;
}
Car(Car&& other) {
this->Name = other.Name;
this->Year = other.Year;
this->Engine = other.Engine;
this->Price = other.Price;
}
void operator= (Car& other) {
this->Name = other.Name;
this->Year = other.Year;
this->Engine = other.Engine;
this->Price = other.Price;
}
inline std::string GetName() const { return Name; }
inline short GetYear() const { return Year; }
inline float GetEngine() const { return Engine; }
inline float GetPrice() const { return Price; }
inline void SetName(std::string n) { Name = n; }
inline void SetYear(short y) { Year = y; }
inline void SetEngine(float e) { Engine = e; }
inline void SetPrice(float p) { Price = p; }
void InitCar(std::string name, short year, float engine, float price) {
Name = name;
Year = year;
Engine = engine;
Price = price;
}
void ShowCar() {
std::cout << "Car_Name: " << Name << ";\nYear: " << Year
<< "; Engine: " << Engine << "; Price: " << Price << "\n";
}
};
然后我创建 Car 对象的向量。
std::vector<Car> base;
现在
base.push_back(Car());
这对于编译器来说是可以的。 接下来也可以:
base.push_back(Car("this_car", 1900, 1.5, 1000));
但是下一个不行:
Car car("that_car", 2001, 3.0, 3000);
base.push_back(car);
编译器说:
没有可用的复制构造函数
当我从 Class Car 中获取 Copy Constructor 时,一切正常。
谁能解释为什么我应该从 Car 类中删除 Copy Constructor?
感谢大家的帮助和耐心。
【问题讨论】:
-
您为什么要编写自己的用户定义的复制、赋值和移动函数?没有理由这样做。
-
好吧,没有我自己的用户定义的复制、分配和移动功能——一切都很好。但我的问题是“为什么我做不到?”
-
当然效果很好,因为这些函数的编译器版本就是这样设计的。您所做的只是让错误更容易发生。
-
编译器是对的,没有copy-constructor。作为提示,您的移动构造函数不会移动任何东西,它只是复制所有内容。
-
这是在不必要时编写自己的运算符的另一个缺点——您失去了编译器能够优化移动和复制的所有优势。一旦您介入并编写自己的代码,您将负责所有这些工作。
标签: c++ copy-constructor