Please use the 'Insert Code' button, and put your fomatted code betweeen the "[ code ]" and "[ / code ]" tags to make it easier for everyone to read:-)
You need to make a couple of changes on thsi one.
The basic constructor
1 2 3 4 5
|
test(int a)
{
a=a;
cout<<a;
}
|
needs to have a different parameter name.
Currently it does NOT set the private variable a as the parameter a is considered more local in scope.
Change to
1 2 3 4 5
|
test(int b)
{
a=b;
cout<<a;
}
|
and it works fine.
Note that this sort of error, where a parameter name overrides an atribute name, can be very difficult to find in a large project.
Secondly you need to change the varaible name for the test of the parameterised constructor as you alreadsy have a vaiable t.
try
1 2 3 4 5 6
|
void main()
{
test t;
test t2(5);
test t1=t2;
}
|
I have added an overload of the operator << to allow you to output the value of a in an instance of test so you can see it all working.
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
|
#include <iostream>
using namespace std;
class test
{
int a;
public:
test()
{
a=0;
cout<<a;
}
test(int b)
{
a=b;
cout<<a;
}
test(test &t) //copy constructor
{
a=t.a;
cout << "Copy! ";
}
friend ostream& operator<<(ostream & os,const test &t);
};
ostream& operator<<(ostream & os,const test &t)
{
os << t.a;
return os;
};
int main()
{
test t;
cout << t << endl;
test t1(5);
cout << t1 << endl;
test t2=t1;
cout << t2 << endl;
test t3(t2);
cout << t3 << endl;
system("pause");
return 0;
}
|
You can also change the parameterised constructor back to your original version in the above to see the effect of it hiding the private variable.