代碼 1:
class CVector {
public:
int x, y;
CVector() {};
CVector(int a, int b) :x(a), y(b) {}
};
CVector operator- (const CVector& lhs, const CVector& rhs)
{
CVector temp;
temp.x = lhs.x - rhs.x;
temp.y = lhs.y - rhs.y;
return temp;
}
int main()
{
CVector foo(2, 3);
CVector bar(3, 2);
CVector result;
result = foo - bar;
cout << result.x << ',' << result.y << endl;
}
代碼 2:
class CVector {
public:
int x, y;
CVector() {};
CVector(int a, int b) :x(a), y(b) {}
};
CVector operator- (const CVector& lhs, const CVector& rhs)
{
return CVector(lhs.x - rhs.x, lhs.y - rhs.y);
}
int main()
{
CVector foo(2, 3);
CVector bar(3, 2);
CVector result;
result = foo - bar;
cout << result.x << ',' << result.y << endl;
}
這兩段代碼操作相同。我想知道為什么我們可以寫作CVector(lhs.x - rhs.x, lhs.y - rhs.y)。這是什么意思?當我們使用一個沒有名字的類時會發生什么?
uj5u.com熱心網友回復:
為什么我們可以寫
CVector(lhs.x - rhs.x, lhs.y - rhs.y)。這是什么意思?當我們使用一個沒有名字的類時會發生什么?
該運算式CVector(lhs.x - rhs.x, lhs.y - rhs.y)使用引數化構造 函式通過傳遞引數和CVector::CVector(int, int)來構造 a 。就像and使用引數化建構式一樣,運算式也使用引數化 ctor。CVectorlhs.x - rhs.xlhs.y - rhs.yCVector foo(2, 3); CVector bar(3, 2)CVector(lhs.x - rhs.x, lhs.y - rhs.y)
您可以通過在引數化建構式中添加 a 來確認這一點,cout如下所示:
#include <iostream>
class CVector {
public:
int x, y;
CVector() {};
CVector(int a, int b) :x(a), y(b) {
std::cout<<"paremterized ctor used"<<std::endl;
}
};
CVector operator- (const CVector& lhs, const CVector& rhs)
{
return CVector(lhs.x - rhs.x, lhs.y - rhs.y); //this uses the parameterized ctor
}
int main()
{
CVector foo(2, 3);
CVector bar(3, 2);
CVector result;
result = foo - bar;
std::cout << result.x << ',' << result.y << std::endl;
}
上述程式的輸出是:
paremterized ctor used
paremterized ctor used
paremterized ctor used
-1,1
請注意,在上面顯示的輸出中,對引數化 ctor 的第三次呼叫是由于 return 陳述句return CVector(lhs.x - rhs.x, lhs.y - rhs.y);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/457931.html
上一篇:Php如果函式在類外被呼叫
