#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
void set_data(int n,char *p,char s);
void display();
private:
int num;
char name[20];
char sex;
};
void Student::set_data(int n,char *p,char s)
{
num=n;
strcpy(name,p);
sex=s;
}
void Student::display()
{
cout<<"num: "<<num<<'\n';
cout<<"name: "<<name<<'\n';
cout<<"sex: "<<sex<<'\n';
}
int main()
{
Student s1,s2;
s1.set_data(1,"He",'f');
s2.set_data(2,"She",'h');
s1.display();
s2.display();
cout<<sizeof(s1);
return 0;
}
问题:
cpp:14:6: error: ‘void Student::set_data(int, char*, char)‘ is private
cpp:29:30: error: within this context
:29:30: warning: deprecated conversion from string constant to ‘char*‘ [-Wwrite-strings]
cpp:14:6: error: ‘void Student::set_data(int, char*, char)‘ is private
cpp:30:31: error: within this context
cpp:30:31: warning: deprecated conversion from string constant to ‘char*‘ [-Wwrite-strings]
cpp:20:6: error: ‘void Student::display()‘ is private
cpp:31:19: error: within this context
cpp:20:6: error: ‘void Student::display()‘ is private
cpp:32:19: error: within this context
cpp: In function ‘void display()‘:
cpp:22:20: error: ‘num‘ was not declared in this scope
cpp:23:22: error: ‘name‘ was not declared in this scope
cpp:24:21: error: ‘sex‘ was not declared in this scope
cpp:10:9: error: ‘int Student::num‘ is private
cpp:31:11: error: within this context
cpp:31:13: error: ‘display‘ was not declared in this scope
结果在原有的输出上增加了输出了28。
解释:
将stud1的属性--num,name,sex所占的字节长度输出出来了。
28=1*4+20*1+1*1+1*1+1*1+1*1
原文:http://blog.csdn.net/ljd939952281/article/details/44275323