tsgfx 2022-05-10 15:00 采纳率: 83.3%
浏览 35
已结题

分文件编写后报错,是为什么?(关键词-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

  • 写回答

1条回答 默认 最新

  • 程序喵正在路上 后端领域新星创作者 2022-05-10 15:14
    关注

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

    #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
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月18日
  • 已采纳回答 5月10日
  • 创建了问题 5月10日

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line