nine_forever
nine_forever
2020-06-11 13:08
采纳率: 50%
浏览 312

为什么构造函数不含有默认参数后就提示默认构造函数已被删除?

#include<iostream>
#include<math.h>
using namespace std;

class myPoint {
public:
    myPoint(double x0  , double y0 ) :x(x0), y(y0) {}
    myPoint(myPoint& np) :x(np.x), y(np.y) {}
    //得到X或Y坐标
    double GetX() { return x; }
    double GetY() { return y; }
    //设置X或Y坐标
    void SetX(double x0) { x = x0; }
    void SetY(double y0) { y = y0; }
    //设置点坐标
    void SetPoint(double x0, double y0) { x = x0; y = y0; }
    void SetPoint(myPoint& np) { x = np.x; y = np.y; }
    //计算三角形边长
    double  GetLength(myPoint p) {
        return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
    }
    void Printit() { cout << " (" << x << "," << y << ") "; }
private:
    double x, y;
};

class Triangle
{
public:
    //计算三角形面积
    double area(double a, double b, double c);
    //计算三角形周长
    double perimeter(double a, double b, double c)
    {
        return a + b + c;
    }
    myPoint p1, p2, p3;
};

double Triangle::area(double a, double b, double c)
{
    double p = (a + b + c) / 2;
    return sqrt(p * (p - a) * (p - b) * (p - c));
}

int main()
{
    Triangle t1;
    t1.p1.SetPoint(0.0, 0.0);
    t1.p2.SetPoint(4.0, 0.0);
    t1.p3.SetPoint(0.0, 3.0);
    cout << "The triangle's area is  " << t1.area(t1.p1.GetLength(t1.p3), t1.p2.GetLength(t1.p1), t1.p2.GetLength(t1.p3)) << endl;
    cout << "The triangle's area is  " << t1.perimeter(t1.p1.GetLength(t1.p3), t1.p2.GetLength(t1.p1), t1.p2.GetLength(t1.p3)) << endl;
    return 0;
}



图片说明

在给构造函数的每个形参都加上默认参数就好了,请问是什么原因

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • caozhy
    已采纳

    因为没有无参数构造函数

    要么:

    myPoint(double x0 , double y0 ) :x(x0), y(y0) {}
    ->
    myPoint(double x0 =0 , double y0 =0) :x(x0), y(y0) {}

    要么加上

    myPoint() :x(0), y(0) {}

    问题解决的话,请点下采纳

    点赞 评论

相关推荐