Some program with classes


So i have wrote this program and when i run it it should show(-1.1, 2.2, 3.3) but it wont run, can you help me find the mistake?




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

class Punct3D{
public:

    Punct3D(double x=0, double y=0, double z=0){
        setX(x);
        setY(y);
        setZ(z);
    }
    double getX(){return x;}
    void setX(double x){this->x = x;}
    double getY(){return y;}
    void setY(double y){this->y = y;}
    double getZ(){return z;}
    void setZ(double z){this->z = z;}
private:
    double x;
    double y;
    double z;
};

ostream& operator<<(ostream& o, Punct3D& p)
{
    Punct3D pct;
    o << p.getX() << "," <<p.getY() << "," <<p.getZ() <<"]";
    return p;
}


int main(){
Punct3D pct(-1.1, 2.2, 3.3);

cout << "Punct3D: " << pct << endl;

 return 0;
}
Last edited on
Two small issues. First, in the function to print, you're returning p rather than o. It's a ostream function, meaning it's expecting you to return the stream, not an object.

Second, you made the function to overload the << operator, but you didn't make it a friend function of the class, so that function can't access any of the private variables in the class (or as my professor likes to say, it can't access it's private parts).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

using namespace std;

class Punct3D {
public:

	Punct3D(double x = 0, double y = 0, double z = 0) {
		setX(x);
		setY(y);
		setZ(z);
	}
	double getX() { return x; }
	void setX(double x) { this->x = x; }
	double getY() { return y; }
	void setY(double y) { this->y = y; }
	double getZ() { return z; }
	void setZ(double z) { this->z = z; }

	friend ostream& operator<<(ostream& o, Punct3D& p);

private:
	double x;
	double y;
	double z;
};

ostream& operator<<(ostream& o, Punct3D& p)
{
	Punct3D pct;
	o << p.getX() << "," << p.getY() << "," << p.getZ() << "]";
	return o;
}


int main() {
	Punct3D pct(-1.1, 2.2, 3.3);

	cout << "Punct3D: " << pct << endl;

	return 0;
}
Ok, i understand now, thank you very much!
Registered users can post here. Sign in or register to post.