在C ++中创建具有2个双精度值的类

在C ++中,我试图创建一个包含两个双精度值的Point2D类。所有数据成员和功能都应公开。

对于公众成员应该有

  • 双倍x
  • 双y

对于构造函数

  • 默认构造函数应将x和y初始化为0.0

  • Point2D(double in_x,double in_y)

    • 将x和y设置为in_x和in_y

对于非成员函数

  • void GetResult(Point2D p1,Point2D p2)

    • 同时输出x和y值

这是我到目前为止的代码,有人可以指出我的错误吗?

Point2D.h

#ifndef POINT2D_H
#define POINT2D_H

class Point2D
{
public:
    double x;
    double y;

Point2D();
Point2D(double,double);

};

void GetResult(Point2D,Point2D);

#endif

Point2D.cpp

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

Point2D::Point2D()
{
    x = 0.0;
    y = 0.0;
}

Point2D::P1(double in_x,double in_y)
{
    x = in_x;
    y = in_y;
}

Point2D::P2(double in_x,double in_y)
{
    x = in_x;
    y = in_y;
}

void GetResult(Point2D P1,Point2D P2)
{
    cout << P1.x << " " << P1.y << endl;
    cout << P2.x << " " << P2.y << endl;
}

TestCheckPoint1.cpp

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

int main()
{
    Point2D Point1;
    Point1.x = 1.0;
    Point1.y= 2.0;

    Point2D Point2;
    Point2.x= 1.0;
    Point1.y= 2.0;

    GetResult(Point1,Point2);
}
Hh708870464 回答:在C ++中创建具有2个双精度值的类

您已经接近了,但是很显然您对重载的构造函数和声明类的实例有一些误解。对于初学者,您不需要功能:

Point2D::P1(double in_x,double in_y)
{
    x = in_x;
    y = in_y;
}

Point2D::P2(double in_x,double in_y)
{
    x = in_x;
    y = in_y;
}

您的Point2D类只需要一个带有两个double值的构造函数,例如

Point2D::Point2D(double in_x,double in_y)
{
    x = in_x;
    y = in_y;
}

然后在main()中,您需要声明并初始化Point2D的默认构造两个实例,以为x和{{1}提供所需的值},然后再调用y,例如

GetResult

注意:您可以提供允许初始化类成员的初始化列表,请参见Constructors and member initializer lists。您可以为构造函数提供初始化列表例如,#include <iostream> #include "Point2D.h" using namespace std; int main() { Point2D Point1 (1.0,2.0); Point2D Point2 (1.0,2.0); GetResult(Point1,Point2); } 和重载Point2D() : x(0),y(0) {};。如果使用{{1创建,则您的构造函数定义将简单地为Point2D(double,double);,并且编译器会将Point2D::Point2D(double in_x,double in_y) : x(in_x),y(in_y) {}初始化为x,y }}或将0,0设置为Point2D Point1;提供的值)

您在x,y的内容周围包括 Header Guards 的工作非常出色,可以防止多个文件包含多个文件。 Point2D Point2 (1.0,2.0);的完整头文件和源文件可以是:

Point2D.h

Point2D

使用/输出示例

编译并运行将导致:

#ifndef POINT2D_H
#define POINT2D_H

class Point2D
{
public:
    double x;
    double y;

    Point2D();
    Point2D(double,double);

};

void GetResult(Point2D,Point2D);

#endif

注意:根本不需要在#include "Point2D.h" #include <iostream> using namespace std; Point2D::Point2D() { x = 0.0; y = 0.0; } Point2D::Point2D(double in_x,double in_y) { x = in_x; y = in_y; } void GetResult(Point2D P1,Point2D P2) { cout << P1.x << " " << P1.y << endl; cout << P2.x << " " << P2.y << endl; } 中使用$ ./bin/TestCheckPoint1 1 2 1 2 ,并且您实际上不应该在任何地方包括整个标准名称空间。只需删除两个呼叫,然后将using namespace std;添加到您的两个main()呼叫和两个对std::的呼叫中即可(或仅使用cout而不是endl)。参见Why is “using namespace std;” considered bad practice?

只需使用:

'\n'

仔细检查一下,如果还有其他问题,请告诉我。

本文链接:https://www.f2er.com/3134071.html

大家都在问