这是你如何做到这一点:
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))
{
}
}
你使用类指针的指针并通过非const引用获取构造函数参数的任何原因? – chris 2013-03-02 15:15:58
您不应该在该函数中使用构造函数,而不是如果您通过引用传入“Triangle”。 – Beta 2013-03-02 15:17:26