我聽說在構造函數中使用初始化列表的優點是不會有額外的類類型對象副本。但是,對於T類構造函數中的以下代碼,它意味着什麼?如果我評論賦值並使用初始化列表,那麼區別是什麼?構造函數中的初始化列表
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
class X {
public:
X(float f_x = 0, float f_y = 0):x(f_x), y(f_y) {}
~X() {}
X(const X& obj):x(obj.x), y(obj.y) {}
friend ostream& operator << (ostream &os, X &obj);
private:
float x;
float y;
};
ostream& operator << (ostream &os, X &obj)
{ os << "x = " << obj.x << " y = " << obj.y; return os;}
class T {
public:
T(X &obj) : x(obj) { /* x = obj */ }
~T() { }
friend ostream& operator << (ostream &os, T &obj);
private:
X x;
};
ostream& operator << (ostream &os, T &obj)
{ os << obj.x; return os; }
int main()
{
X temp_x(4.6f, 6.5f);
T t(temp_x);
cout << t << endl;
}
不知道有關你的問題,但你可能會想T(X常量和OBJ)。 –
@ K-ballo:是的,我忘記了,謝謝。 – user767451