分文件编写后报错,是为什么?(关键词-class)

.h文件

#ifndef MYPOINT_H
#define MYPOINT_H
class Mypoint
{
    public:
        Mypoint();
        Mypoint(double newX, double newY);
        double x;
        double y;
        double getX();
        double getY();
        double distance(Mypoint point1, Mypoint point2);
};
#endif

.cpp文件

#include <cmath>
#include "Mypoint.h"

    Mypoint::Mypoint()
    {
        x = 0;
        y = 0;
    }
    Mypoint::Mypoint(double newX, double newY)
    {
        x = newX;
        y = newY;
    }
    double Mypoint::getX()
    {
        return x;
    }
    double Mypoint::getY()
    {
        return y;
    }
    double Mypoint::distance(Mypoint point1, Mypoint point2)
    {
        return pow((point1.getX() - point2.getX()) * (point1.getX() - point2.getX()) + (point1.getY() - point2.getY()) * (point1.getY() - point2.getY()), 0.5);
    }


测试文件

#include <iostream>
#include "Mypoint.h"
using namespace std;
                                                                                                                                                                                                                                                    ;;
int main()
{
  Mypoint point1;
  Mypoint point2;
  point1.Mypoint(0, 0);
  point2.Mypoint(10, 30.5);
  point1.distance(Mypoint point1, Mypoint point2);
   return 0;
}

最后报错了

img

构造方法不能手动调用的,你等一下我改一下

#include <iostream>
#include "Mypoint.h"
using namespace std;

int main()
{
    //编译器调用无参构造
    Mypoint p1;     
    
    //编译器调用有参构造
    Mypoint point1(0,0);
    Mypoint point2(5,12);
    
    //函数声明的时候参数要写类型,调用的时候不用哦
    cout << "两点之间距离:" << point1.distance(point1, point2) << endl;

    return 0;
}

主函数改成这样试试


头文件建议把属性和方法分开

#ifndef MYPOINT_H
#define MYPOINT_H
class Mypoint
{
public:
    double x;
    double y;
public:
    Mypoint();
    Mypoint(double newX, double newY);
    double getX();
    double getY();
    double distance(Mypoint point1, Mypoint point2);
};
#endif

有帮助的话可以采纳一下吗,还有不懂可以问我哦