[英]returning object from class function c++
假設我們有一個像下面的函數
Car buyCar();
我的問題是要使此函數起作用,必須在Car類中使用哪種方法? 是默認構造函數嗎?
Car buyCar();
沒有人們認為的效果,請查找“最令人煩惱的解析”: https ://en.wikipedia.org/wiki/Most_vexing_parse
由於C ++語法中的古怪之處,語法Type instance()
實際上被解釋為聲明而不是調用。 請參見調用默認構造函數
要調用默認的無參數類型的構造函數,您需要省略括號。
Car buyCar; // allocates and constructs a `Car` on the stack
但是,如果要在堆上分配(使用new
),則使用括號確實可以。
使用原始指針:
Car* buyCar = new Car();
使用智能指針:
unique_ptr<Car> buyCar = make_unique<Car>(); // <-- parens used because this is actually calling `make_unique` (a function) which indirectly calls the constructor
在初始化列表中,您確實使用括號來調用字段的默認構造函數-但這在很大程度上沒有意義,因為該類型的默認(編譯生成的)構造函數已經可以做到這一點:
class Inner {
public:
Inner() {
}
}
class Container {
private:
Inner innerInstance;
public:
Container() :
innerInstance() // <-- parens used here
{ }
}
此方法應返回Car類的對象。 默認構造函數是自動可用的,不需要單獨定義。 還可以創建自定義構造函數,並使用所需的值對其進行初始化。 因此,您可以根據需要返回默認構造函數或自定義構造函數。
我為你寫了一個小例子
#include <iostream>
using namespace std;
class Car {
public :
Car(): carnum(0) {
cout << "default constructor " << carnum << endl;
}
Car (int n) : carnum (n) {
cout << "Argument constructor " << carnum << endl;
}
Car& operator = (const Car& car) {
carnum = car.carnum;
cout << "operator = " << carnum << endl;
return *this;
}
Car (const Car& car) {
carnum = car.carnum;
cout << "Copy constructor " << carnum << endl;
}
Car buyCar() {
return *this;
}
int carnum;
};
int main() {
Car aCar, theCar(2); // default constructor for aCar and argument constructor for theCar;
cout << endl;
aCar = theCar.buyCar(); // copy constructor and equal operator are called
cout << endl;
Car bCar(aCar.buyCar()); // only copy constructor is called here
cout << endl;
return 0;
}
因此,這取決於上下文,您如何使用buyCar()
函數。
我假設buyCar()
是class Car
的成員函數
即使class Car
沒有Constructors
和Assignment Operator
,函數buyCar()
仍將與默認構造函數和賦值運算符一起使用。
但是,如果您的類處理動態內存,那么如果該類具有一些動態創建/分配的數據成員,則該類應具有Copy Constructor
, Move Constructor
, Assignment Operator
和Move Assignment operator
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.