سؤال

I am trying to create my first class in c++. I am making file called geometryitems.cpp and doing this:

using namespace std;

class Point
{
    double x, y, z;
public:
    // constructor
    Point(double x, double y, double z)
        {

        }

    // copy constructor
    Point(const Point& pnt)
        {
            x = pnt.x;
            y = pnt.y;
            z = pnt.z;
        }

    void display()
        {
            cout << "Point(" << x << ", " << y << ", " << z << ")";
        }
};

Then I call it from another file like this:

#include <iostream>
#include <cstdio>
#include "geometryitems.cpp"
using namespace std;

int main()
{
    // initialise object Point
    Point pnt = Point(0, 0, 0);
    cout << "Point initialisation:" << endl;
    pnt.display();

    double t = 0;
    cout << endl << t << endl;

    Point pnt2 = pnt;
    pnt2.display();

    // keep the terminal open
    getchar();

    return 0;
}

Here is the output:

t is shown as normal 0 but other zeros are some other numbers. I would understand if they were just very-very small numbers but there are also very-very big ones...

Why are the zeros in Point shown as such strange numbers? Is there a way to make it looking as normal zeros?

هل كانت مفيدة؟

المحلول

You are not setting the member variables to any value in your constructor:

Point(double x, double y, double z)
{

}

You need

Point(double x, double y, double z) : x(x), y(y), z(z) {}

This initializes your data members x, y, and z using the constructor initialization list.

You should also remove your copy constructor. The compiler-synthesized one will do just fine.

نصائح أخرى

It's empty

Point(double x, double y, double z)
{

}

So, Point pnt = Point(0, 0, 0); doesn't initialize anything. Use member initializer list. Also you can read more about it here.

Point(double x, double y, double z) : x(x), y(y), z(z)
{                                  //^^^^^^^^^^^^^^^^^^
                                   // Initializer list
}

That copy-constructor is copying uninitialized values to another object.

Your constructor is buggy. The members aren't initialized. Change it to:

Point(double x_, double y_, double z_)
: x(x_), y(y_), z(z_)
{
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top