I have
Triangle::Triangle()
{
A = NULL;
B = NULL;
C = NULL;
}
Triangle::Triangle(Point& X,Point& Y, Point& Z)
{
A = new Point;
*A = X;
B = new Point;
*B = Y;
C = new Point;
*C = Z;
}
and
istream& operator>>(istream& in, Triangle& T)
{
Point X,Y,Z;
in>>X>>Y>>Z;
Triangle T(X,Y,Z);
return in;
}
Where Point is another class which defines a point with coordonates X and Y. I don't know how to call the constructor with multiple arguments in the overloaded function. Can you help me?
This is how you do it:
Point px;
Point py;
Point pz;
Triangle trig(px, py, pz);
trig
will be the object, which is an instance of class Triangle
and the above would call the constructor with 3 Point arguments.
Another way is for pointers:
Triangle *pTrig = new Triangle(pX, pY, pZ);
In addition, I suggest, that this would be better:
Triangle::Triangle()
: A(NULL), B(NULL), C(NULL)
{
}
Triangle::Triangle(const Point& X,const Point& Y, const Point& Z)
: A(new Point(X)), B(new Point(Y)), C(new Point(Z))
{
}
Assuming that Point has a copy constructor.
You want to call it from inside the operator>>
function to update argument T, but this won't work, because you cannot call the constructor on something that's already constructed. Instead, what you need is to implement an assignment operator. Please see http://en.wikipedia.org/wiki/Assignment_operator_%28C%2B%2B%29 for more information.
Then you can do T = Triangle(X,Y,Z);
To implement the assignment operator, you can do this:
Triangle& Triangle::operator= (const Triangle& other)
{
if (this != &other) // protect against invalid self-assignment
{
if (A != NULL) delete A;
if (B != NULL) delete B;
if (C != NULL) delete C;
A = new Point(other.A);
B = new Point(other.B);
C = new Point(other.C);
}
return *this;
}
Assuming Point has copy constructors. To implement copy constructors, please see http://en.wikipedia.org/wiki/Copy_constructor
A copy constructor looks like the following, but you need to do it for Point:
Triangle& Triangle::Triangle(const Triangle& other)
: A(new Point(other.A)), B(new Point(other.B)), C(new Point(other.C))
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With