Structures
- A
struct
in C is a type consisting of a sequence of data members. - Some functions/statements are needed to operate the data members of an object of a struct type. | ```c struct Student { char name[4]; int born; bool male; };
struct Student stu; strcpy(stu.name, “Yu”); stu.born = 2000; stu.male = true;
|  | 结构体<br />- 数据操作要非常小心<br />- 不经意间会发生越界<br /> |
| --- | --- | --- |
Classes
- You should be very careful to manipulated the data members in a `struct` object.
- Can we improve `struct` to a better one?
- Yes, it is **class**! We can put some member functions in it.
```cpp
class Student
{
public:
char name[4];
int born;
bool male;
void setName(const char * s)
{
// 成员函数,专门操作类中的数据
strncpy(name, s, sizeof(name));
}
void setBorn(int b)
{
// pass
}
Student yu;
yu.setName("Yu");
// 数据操作更加安全
Access Specifiers访问限定符
- You can protect data members by access specifier private.
- Then data member can only be accessed by well designed member functions.
- 私有成员变量只能被类内的成员函数访问
```cpp
class Student
{
private:
char name[4];
int born;
bool male;
public:
void setName(const char * s)
{
} void setBorn(int b) {} }strncpy(name, s, sizeof(name));
Student yu; yu.born = 2001; // 无法修改
Member Functions<br />A member function can be defined inside or outside class.
<br />成员函数实现可以放到类内,也可只在类内进行声明,
```cpp
class Student
{
private:
char name[4];
int born;
bool male;
public:
// 类内中定义了这个函数的具体实现,这个函数就是inline函数
void setName(const char * s)
{
strncpy(name, s, sizeof(name));
}
void setBorn(int b)
{
born = b;
}
void setGender(bool isMale);
void printInfo();
};
inline void Student::setGender(bool isMale)
{
male = isMale;
}
void Student::printInfo()
{
cout << "Name: " << name << endl;
cout << "Born in " << born << endl;
cout << "Gender: " << (male ? "Male" : "Female") << endl;
}
File Structures
那函数实现到底应该放在什么地方:
- 如果是特别简单的函数实现,可以放在类内实现
- 如果是复杂函数,建议放在类的外部定义。推荐类的声明放在头文件,函数的定义放在cpp文件,cpp文件中红应该include对应的头文件。
The source code can be placed into multiple files
// student.hpp
class Student
{
private:
char name[4];
int born;
bool male;
public:
void setName(const char * s)
{
strncpy(name, s, sizeof(name));
}
void setBorn(int b)
{
born = b;
}
void setGender(bool isMale);
void printInfo();
};
// student.cpp
#include "student.hpp"
void Student::setGender(bool isMale)
{
male = isMale;
}
void Student::printInfo()
{
cout << "Name: " << name << endl;
cout << "Born in " << born << endl;
cout << "Gender: " << (male ? "Male" : "Female") << endl;
}
:::info
include 后面有时候是<>
,有时候是""
,有什么说法:
<>
:在编译器指定的include路径,寻找头文件""
:不光从编译器指定的include路径中寻找,还从当前目录中寻找 :::