#include <iostream>
using namespace std ;
class Student
{
private:
int num ;
char name [ 20 ] ;
char sex ;
public:
void set_data ( int n , char *p , char s )
{
num = n ;
strcpy ( name , p );
sex = s ;
}
void display ()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex" << sex << endl;
}
};
int main()
{
Student stud1 , stud2 ; //(1)
stud1.set_data(1,"he",'f');//(2)
stud2.set_data(2,"she",'m');//(3)
stud1.display();//(4)
stud2.display();//(5)
return 0;
}
运行结果:
main()中语句1后调用stud1.display();
结果:
main()中语句(3)后调用stud2.sex='f';
结果:出现:C:\Documents and Settings\user\桌面\程序设计\Cpp1.cpp(44) : error C2248: 'sex' : cannot access private member declared in class 'Student'
C:\Documents and Settings\user\桌面\程序设计\Cpp1.cpp(13) : see declaration of 'sex'
的错误提示!!!!
更改如下:把 char sex ; 改成公有的部分(如下)
#include <iostream>
using namespace std ;
class Student
{
private:
int num ;
char name [ 20 ] ;
public:
char sex ;
void set_data ( int n , char *p , char s )
{
num = n ;
strcpy ( name , p );
sex = s ;
}
void display ()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex" << sex << endl;
}
};
int main()
{
Student stud1 , stud2 ; //(1)
stud1.set_data(1,"he",'f');//(2)
stud2.set_data(2,"she",'m');//(3)
stud2.sex='f';
stud1.display();//(4)
stud2.display();//(5)
return 0;
}
运行结果:
