首页 > 解决方案 > 使用 OOP 创建二维坐标系程序

问题描述

我正在编写一个代码来计算和显示二维坐标系统中的线长。但是,我的代码中有一些错误,我不确定如何修复它们。我编译时的错误如附图所示。编码错误

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

class Line
{ private:
 int x1, y1, x2, y2;
 public:
 Line() : x1(0), y1(0), x2(0), y2(0) // default constructor 
 {
 Line ( int a, int b, int c, int d ) // constructor
 {
  x1 = a, y1 = b, x2 = c, y2 = d;
 };

 void setLine() ; // mutator function
 void getLine() const; // accessor function
 double getLength() const; // returns length of a line
}

void Line :: setLine()
{ cout << "Enter x-coordinate and y-coordinate of first endpoint : ";
 cin >> x1 >> y1;
 cout << "Enter x-coordinate and y-coordinate of second endpoint : ";
 cin >> x2 >> y2;
}
double Line :: getLine() const
{ cout << "\nThe endpoints of the line are : ";
 cout << "( " << x1 << ", " << y1 << " ) and ";
 cout << "( "<< x2 << ", " << y2 << " )" << endl;
}
double Line :: getLength() const
{ return sqrt ( pow(( x1 - x2), 2) + pow ((y1 - y2), 2) );
}
int main()
{ Line myline{ 2, 3, 4, 5};
 myline.getLine();
 cout << "Length of the line = " << myline.setLength() <<endl;
 cout << "Edit the line : " << endl;
 myline.setLine();
 myline.getLine();
 cout << "Length of the line = " << myline.getLength() <<endl;
 return 0;
}
};

标签: c++functionoopvoid

解决方案


这看起来像是一个非常糟糕的尝试编写一些 C++ 代码(充满语法错误和糟糕的写作错误)。我建议您在尝试此操作之前先遵循 C++ tuto...

对于您的一段代码,这应该有效,但如果您不明白为什么它有效并且您的代码无效,请至少学习一堂 c++ 课程:

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

class Line
{ 
private:
    int x1, y1, x2, y2;
public:
    // default constructor 
    Line() : x1(0), y1(0), x2(0), y2(0)
    {
        // empty brackets needed
    };
    
    Line ( int a, int b, int c, int d ) : x1(a), y1(b), x2(c), y2(d) // constructor
    {
        
    };

    void setLine() ; // mutator function
    void getLine() const; // accessor function
    double getLength() const; // returns length of a line
}; // need ';' after class definition

void Line::setLine()
{ 
    cout << "Enter x-coordinate and y-coordinate of first endpoint : ";
    cin >> x1; 
    cin >> y1;
    cout << "Enter x-coordinate and y-coordinate of second endpoint : ";
    cin >> x2;
    cin >> y2;
}

void Line::getLine() const  // here is void not "double". Be carefull of copy past
{
    cout << "\nThe endpoints of the line are : ";
    cout << "( " << x1 << ", " << y1 << " ) and ";
    cout << "( "<< x2 << ", " << y2 << " )" << endl;
}

double Line::getLength() const
{ 
    return sqrt ( pow(( x1 - x2), 2) + pow ((y1 - y2), 2) );
}

// main can't be inside a class
int main()
{ 
    Line myline{ 2, 3, 4, 5};
    myline.getLine();
    cout << "Length of the line = " << myline.getLength() <<endl; // getLength, not setlength
    cout << "Edit the line : " << endl;
    myline.setLine();
    myline.getLine();
    cout << "Length of the line = " << myline.getLength() <<endl;
    return 0;
}

推荐阅读