我叫淳子 发表于 2016-4-19 18:01:09

多参构造函数的对象怎么作为其他函数的参数

#include <iostream>
#include <cstring>
#include<math.h>
using std::cout;
using std::endl;
class Point{
private:
      double x, y;
public:
      Point(double xx, double yy)
      {
              x=xx;
              y=yy;
          }
      double getX()
      {
              return x;
          }
      double getY()
      {
              return y;
          }
};
class Triangle{
private:
      Point a, b, c;
public:
      Triangle():a(5.8,3.3),b(3.3,4.2),c(6.6,7.8)
      {}
      Triangle(double x1,double y1,double x2,double y2,double x3,double y3):a(x1,y1),b(x2,y2),c(x3,y3)
      {}
      Triangle(Point p1,Point p2,Point p3){}//这边要怎么初始化?
      double getSideA()
      {
              double sidea;
              sidea=sqrt((b.getX()-c.getX())*(b.getX()-c.getX())+(b.getY()-c.getY())*(b.getY()-c.getY()));
              return sidea;
          }
      double getSideB()
      {
              double sideb;
              sideb=sqrt((a.getX()-c.getX())*(a.getX()-c.getX())+(a.getY()-c.getY())*(a.getY()-c.getY()));
              return sideb;
          }
      double getSideC()
      {
              double sidec;
              sidec=sqrt((b.getX()-a.getX())*(b.getX()-a.getX())+(b.getY()-a.getY())*(b.getY()-a.getY()));
              return sidec;
          }
      double getArea()
      {
              double s,area,x,y,z;
              x=getSideA();
              y=getSideB();
              z=getSideC();
              s=getSideA()+getSideB()+getSideC();
              area=sqrt(s*(s-x)*(s-y)*(s-z));
              return area;
          }
      double getPeri()
      {
              double s;
              s=getSideA()+getSideB()+getSideC();
              return s;
          }
};
int main()
{
        Triangle T1(1.7,8.8,4.3,2.2,6.6,7.7),T2;
        cout<<"T1的面积为:"<<T1.getArea()<<endl;
        cout<<"T1的周长为:"<<T1.getPeri()<<endl;
        cout<<"T2的面积为:"<<T2.getArea()<<endl;
        cout<<"T2的周长为:"<<T2.getPeri()<<endl;
        return 0;
}

LeoChou 发表于 2016-4-20 09:45:08

不清楚你想问什么,Triangle(Point p1,Point p2,Point p3){a=p1;b=p2;c=p3;}?

我叫淳子 发表于 2016-4-20 17:44:47

LeoChou 发表于 2016-4-20 09:45
不清楚你想问什么,Triangle(Point p1,Point p2,Point p3){a=p1;b=p2;c=p3;}?

是的,但是这样编译会出问题

我叫淳子 发表于 2016-4-20 17:48:13

LeoChou 发表于 2016-4-20 09:45
不清楚你想问什么,Triangle(Point p1,Point p2,Point p3){a=p1;b=p2;c=p3;}?

因为Point对象的构造函数是多参的,覆盖了无参的构造函数,这样就不能直接Point p1,Point p2,Point p3直接作为Triangle函数的形参。编译会报错。

LeoChou 发表于 2016-4-21 09:11:23

那就再写一个Point的无参构造函数或者为有参构造函数添加默认值Point(double xx=0, double yy=0) 。

我叫淳子 发表于 2016-4-21 11:31:36

LeoChou 发表于 2016-4-21 09:11
那就再写一个Point的无参构造函数或者为有参构造函数添加默认值Point(double xx=0, double yy=0) 。

原来默认值是这样用的啊,谢谢大神啊。
页: [1]
查看完整版本: 多参构造函数的对象怎么作为其他函数的参数