c++ - 计算两点间距离时的编译错误

标签 c++ oop

我不明白为什么这个程序不能运行。我确定这是基本的东西。

#include <iostream>
using namespace std;
class MyPoint
{
    int x;
    int y;
public:
    MyPoint()
    {
        x = 0;
        y = 0;
    }

    MyPoint(int newX, int newY)
    {
        x = newX;
        y = newY;
    }

    int getX()
    { 
        return x;
    }

    int getY()
    {
        return y;
    }

    int distance(MyPoint newPoint)
    {
      distance = x - newPoint.getX();//need absolute value function
      return distance;
    };

  int main()
  {
    MyPoint point1(0,0);
    MyPoint point2(5,5);

    cout << "THe distance between the two circles is " << point1.distance(point2) << endl;

    return 0;
  }

我试图找到两点之间的距离,只是为了测试以确保我正确使用类。我只是使用 x 点而已。现在代码无法编译。

最佳答案

现在,您的第一个问题是 main 在类内部 - 您忘记了 distance 函数后的大括号。你有结束类描述的分号,但你总共有一个大括号太少了。

您的第二个问题是您在名为 distance 的函数中使用了名为 distance 的变量。不要名字冲突,它们会让小猫哭泣。

你的第三个问题是我刚才提到的distance变量应该是int类型。

作为另一条一般性建议,当您的代码无法编译时,编译器会给您错误消息。发布这些内容很有帮助。

关于c++ - 计算两点间距离时的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9147644/

相关文章:

c++ - 将所有成员从一个结构复制到另一个结构

c++ - 如何从 C++ 中的网络摄像头读取输入?

使用魔术方法 __get 和 __set 的 PHP 可见性

language-agnostic - OOP 的重点是什么?

c# - 如何在不知道提前指定数量的情况下创建对象数组

c++ - 使用 LLVM 在 JXcore 中可用的 Node 插件

c++ - 使用 boost::program_options 禁止无符号值的负参数

c++ - 不同类中的前置和后置增量运算符

C++ 基本类构造函数

oop - 当第一个参数为 nil 时无法调用方法?