Code 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;
}
Code 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;
}
These two pieces of code operate identically. I want to know why we can write CVector(lhs.x - rhs.x, lhs.y - rhs.y)
. What does it mean? What happens when we use a class without a name?
CodePudding user response:
why we can write
CVector(lhs.x - rhs.x, lhs.y - rhs.y)
. What does it mean? What happens when we use a class without a name?
The expression CVector(lhs.x - rhs.x, lhs.y - rhs.y)
uses the pameterized constructor CVector::CVector(int, int)
to construct a CVector
by passing the arguments lhs.x - rhs.x
and lhs.y - rhs.y
. Just like CVector foo(2, 3);
and CVector bar(3, 2)
uses the parameterized constructor, the expression CVector(lhs.x - rhs.x, lhs.y - rhs.y)
also uses the parameterized ctor.
You can confirm this by adding a cout
inside the parameterized constructor as shown below:
#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;
}
The output of the above program is:
paremterized ctor used
paremterized ctor used
paremterized ctor used
-1,1
Notice in the output shown above, the third call to the parameterized ctor is due to the return statement return CVector(lhs.x - rhs.x, lhs.y - rhs.y);