Home > Back-end >  How ???? "reference in class" c
How ???? "reference in class" c

Time:11-13

I want to slove this problem I can't get the result I want

// main.cpp
#include "Point.h"
#include <iostream>
using namespace std;


int main(void) {
    double x, y;
    Point p{ 10.5, 20.99 };
    p.info();
    p.get(x, y);
    cout << x << ", " << y << endl;
    return 0;
}

//Headerfile Point.h
#include <iostream>
using namespace std;
class Point {
private:
    double x, y;
public:
    Point(double P_x , double P_y) {
        x = P_x;
        y = P_y;
    }
    void info(void) {
        cout << "(x,y) = " << x << ", " << y << endl;
    }
    double getx(double &x) {
        x;
        return 0;
    }
    double gety(double &y) {
        y;
        return 0;
    }
    void get(double& x, double& y) {

        getx(x), gety(y);
    }
};

Output My wrong result

(x,y) = 10.5, 20.99

-9.25596e 61, -9.25596e 61

But I want to get this re

(x,y) = 10.5, 20.99

10.5, 20.99

CodePudding user response:

Here's how to write those get functions properly

double getx() const {
    return x;
}
double gety() const {
    return y;
}
void get(double& x, double& y) const {
    x = getx();
    y = gety();
}

I'm not sure what you thought your version was doing

double gety(double &y) {
    y;
    return 0;
}

Why return 0; when you want to return y? What does y; on its own do? (The answer is nothing at all). I guess you started with something that was nearly right, and it just got worse the more you tried to fix it.

CodePudding user response:

I found a lot of useless code. I simply removed all the useless code and replaced it with simple getter functions which you can then use as you like in main. It simply tries to make things as simple as possible without the user really knowing what is behind the object implementation. I know this is not the best explanation but the real problem was only in the fact that functions were implemented that could have been implemented differently. I hope I was helpful.

#include <iostream>

using namespace std;

class Point {
    private:
        double x;
        double y;
    public:
        Point(double P_x , double P_y) {
            x = P_x;
            y = P_y;
        }
        
        void info() const {
            cout << "(x,y) = " << this->x << ", " << this->y << endl;
        }
        
        double getx() const {
            return this->x;
        }
        double gety() const {
            return this->y;
        }
};


int main() {
    Point p{ 10.5, 20.99 };
    p.info();
    
    double x = p.getx();
    double y = p.gety();
    
    cout << x << "," << y << endl;
    return 0;
}
  • Related