2013-03-02 81 views
2

我调用构造函数有多个参数

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; 
} 

哪里点是定义与coordonates X和Y 一个点的另一个类,我不知道该怎么称呼与多个参数构造函数的重载函数。你可以帮我吗?

+1

你使用类指针的指针并通过非const引用获取构造函数参数的任何原因? – chris 2013-03-02 15:15:58

+0

您不应该在该函数中使用构造函数,而不是如果您通过引用传入“Triangle”。 – Beta 2013-03-02 15:17:26

回答

3

这是你如何做到这一点:

Point px; 
Point py; 
Point pz; 
Triangle trig(px, py, pz); 

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

另一种方式是指针:

Triangle *pTrig = new Triangle(pX, pY, pZ); 

此外,我认为,这将是更好的:

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)) 
{ 
} 

假设点有一个拷贝构造函数。

你想从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; 
} 

假设点有拷贝构造函数。为了实现拷贝构造函数,请参阅http://en.wikipedia.org/wiki/Copy_constructor

拷贝构造函数如下所示,但你需要做的点:

Triangle& Triangle::Triangle(const Triangle& other) 
    : A(new Point(other.A)), B(new Point(other.B)), C(new Point(other.C)) 
{ 
} 
} 
+0

我试过并给了我“重新定义形式参数'T'” – user2116010 2013-03-02 15:44:03

+0

啊......现在我明白了......您想在运算符>>函数中调用它。不......那不行。让我更新我的答案。 – ruben2020 2013-03-02 15:49:44

+0

太棒了!它正在工作,你也完成了赋值运算符功能。大!非常感谢你! – user2116010 2013-03-02 16:08:47

0

前两个构造函数是默认构造函数覆盖。第三个函数是运算符重载,它重载了>>运算符。你只需要创建一个三角形类的对象如下:

Triangle tr(x,y,z); 

Triangle* tr = new Triangle(x,y,z); 

其中x,y和z是Point类的对象。顺便说一句,正如您在运算符重载(第三个函数)中所看到的那样,您已经创建了类Triangle(Triangle T(X,Y,Z);)的对象。

+0

是的,但运算符重载的参数是第一个构造函数,并且不会传递X,Y和Z的正确值 – user2116010 2013-03-02 15:38:54