使用多个参数调用构造函数

use*_*010 5 c++ constructor arguments

我有

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;
}
Run Code Online (Sandbox Code Playgroud)

其中 Point 是另一个类,它定义了一个带有坐标 X 和 Y 的点。我不知道如何在重载函数中调用具有多个参数的构造函数。你能帮助我吗?

rub*_*020 3

您可以这样做:

Point px;
Point py;
Point pz;
Triangle trig(px, py, pz);
Run Code Online (Sandbox Code Playgroud)

trig将是对象,它是类的实例Triangle,上面将使用 3 个点参数调用构造函数。

另一种方法是指针:

 Triangle *pTrig = new Triangle(pX, pY, pZ);
Run Code Online (Sandbox Code Playgroud)

另外,我建议,这样会更好:

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))
{
}
Run Code Online (Sandbox Code Playgroud)

假设 Point 有一个复制构造函数。

您想从operator>>函数内部调用它来更新参数 T,但这行不通,因为您无法在已经构造的东西上调用构造函数。相反,您需要的是实现一个赋值运算符。请参阅http://en.wikipedia.org/wiki/Assignment_operator_%28C%2B%2B%29了解更多信息。

然后你可以做T = Triangle(X,Y,Z);

要实现赋值运算符,您可以这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

假设 Point 有复制构造函数。要实现复制构造函数,请参阅http://en.wikipedia.org/wiki/Copy_constructor

复制构造函数如下所示,但您需要为 Point 执行此操作:

Triangle& Triangle::Triangle(const Triangle& other)
  : A(new Point(other.A)), B(new Point(other.B)), C(new Point(other.C))
{
}
}
Run Code Online (Sandbox Code Playgroud)