Accessing private members using Operators

my x and y is private so i cant p.x or p.y
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

using namespace std;

class test
{
	private:
		int x;
		int y;
	public:
		test(); // constructors cant be private
		~test();
		test operator+(int);
};
test::test()
{
	cout << "constructing...." << endl;
	x = 0;
	y = 0;
}
test::~test()
{
	cout << "Destructing in...." << endl;
}
test test::operator+(int p)
{
	int newtest;
	
	newtest = x + p.x;
	newtest = y + p.y;
	
	return newtest;
}
int main ()
{
	test constructor;
	test t1,t2,t3;
	
	int a,b;
	
	cout << "enter numbers: ";
	cin >> a >> b;
	
	
	char chooseoperator;
	
	cout << "Choose a operator: ";
	cin >> chooseoperator;
	if(chooseoperator == '+')
	{
		t3 = t1.x + t2.y;
		cout << " t3" << endl;
	}
	
	return 0;
}
the accepted approach is to make x and y have getting and setting functions.

int getx()
{
return x;
}

int setx(int val)
{
x = val;
}

p.getx(); replaces p.x;
Last edited on
the operator + overload is incorrect - from the return statement it seems that you're trying to add 2 test objects, in which case it would be like:
1
2
3
4
5
6
7
8
9
test test::operator+(const test& rhs)
{
	test newtest;

	newtest.x = x + rhs.x;
	newtest.y = y + rhs.y;

	return newtest;
}
also ...
// constructors cant be private

this is incorrect - http://stackoverflow.com/questions/6568486/when-do-we-need-a-private-constructor-in-c
Topic archived. No new replies allowed.