I have to write a C++ code must also perform sorting of multiple objects of the following class:
class student
{
int roll, m[5], total;
bool pass;
char name[30];
public:
void read();
void result();
void print();
void operator=(student&);
friend void sort(student, int);
};
void sort(student var[], int size)
{
int s,t;
for (s = 0; s<size; s++)
for (t = 0; t<size; t++)
{
if (var[s].total<var[t].total) //---------line 22----------
{
student x;
x = var[s];
var[s] = var[t];
var[t] = x;
}
}
}
void student::operator=(student &x)
{
roll=x.roll;
strcpy_s(name,x.name);
for(int v=0;v<5;v++)
m[v]=x.m[v];
total=x.total;
pass=x.pass;
}
void main()
{
student s[4];
int ni, n;
cout<<"Enter number of student records: ";
cin >> n;
for (ni = 0; ni<n; ni++)
{
s[ni].read();
s[ni].result();
}
sort(s, n);
cout<<endl<<"List sorted based on total: "<<endl;
for (ni = 0; ni<n; ni++)
{
s[ni].print();
}
}
I use Visual C++ 2008. When I compiled this code it displays two errors:
Error1 error C2248:'student::total': cannot access private member declared in class 'student'
Error2 error C2248:'student::total': cannot access private member declared in class 'student'
These errors are shown at same line 22 that is while accessing total. Although sort()
is a friend function I get this accessibility error.
I noted that if total declared public, there is no error. but as per class specification it has to be private. Please help me.