学习类与对象,C++中struct与class区别

struct定义类:

struct Student
{
 char _name[20];
 char _gender[3];
 int _age;
 char _school[20];
 void SetStudentInfo(char name[], char gender[], int age, char school[])
 {
  strcpy(_name,name);
  strcpy(_gender,gender);
  _age = age;
  strcpy(_school, school);
 }
 void PrintfStudentInfo()
 {
  cout << _name << "-" << _gender << "-" << _age << "-" << _school << endl;
 }
 //吃饭、睡觉、上课、写作业、考试、编程----功能一般通过函数体现
 void Eat()
 {
  cout << "吃肉" << endl;
 }
 void Exam()
 {
  cout << "考试" << endl;
 }
};
int main()
{
 Student s1, s2, s3;
 s1.SetStudentInfo("熊大", "公", 5, "熊熊乐园");
 s2.SetStudentInfo("熊二", "公", 4, "熊熊乐园");
 s3.SetStudentInfo("光头强", "公", 28, "熊熊乐园");
 s1.PrintfStudentInfo();
 s2.PrintfStudentInfo();
 return 0;
}

class定义类:

class Student
{
private:
 char _name[20];
 char _gender[3];
 int _age;
 char _school[20];
public:
 void SetStudentInfo(char name[], char gender[], int age, char school[])
 {
  strcpy(_name, name);
  strcpy(_gender, gender);
  _age = age;
  strcpy(_school, school);
 }
 void PrintfStudentInfo()
 {
  cout << _name << "-" << _gender << "-" << _age << "-" << _school << endl;
 }
 //吃饭、睡觉、上课、写作业、考试、编程----功能一般通过函数体现
 void Eat()
 {
  cout << "吃肉" << endl;
 }
 void Exam()
 {
  cout << "考试" << endl;
 }
};
int main()
{
 Student s1, s2, s3;
 s1.SetStudentInfo("熊大", "公", 5, "熊熊乐园");
 s2.SetStudentInfo("熊二", "公", 4, "熊熊乐园");
 s3.SetStudentInfo("光头强", "公", 28, "熊熊乐园");
 s1.PrintfStudentInfo();
 s2.PrintfStudentInfo();
 return 0;
}

C++中struct和class的区别是什么?
C++需要兼容C语言,所以C++中struct可以当成结构体去使用。另外C++中struct还可以用来定义类。 和class是定义类是一样的,区别是struct的成员默认访问方式是public,class是struct的成员默认访问方式是private。

你可能感兴趣的:(C++,c++)