c++的类和对象

类和对象

什么是类

把抽象结果(利用面向对象的思维模式,思考、观察出的结果),使用用C++的语法封装出一种类似结构的自定义数据类型(复合数据类型)。

如何设计类
复制代码
struct 结构名
{
    成员函数;   // 结构的成员默认访问权限是public
    成员变量;
};
​
class 类名
{
    成员变量;   // 结构的成员默认访问权限是private
    成员函数;
};
​
注意:在C++中类的结构除了成员的默认访问权限不同,没有任何区别(大师兄说的)。
访问限制符

使用以下关键字修改结构、类的成员,管理它们的访问权限:

复制代码
private: 私有的,被它修饰的成员,只能在类的成员函数内使用。
protected: 保护的,被它修饰的成员,只能在类、子类的成员函数内使用。
public: 公开的,被修饰的成员,可以在任何位置使用。
复制代码
#include <iostream>
using namespace std;
​
struct Student
{
    void in(void)
    {   
        cout << "请输入学生的学号、姓名、年龄、成绩:"; 
        cin >> id >> name >> age >> score;
    }   
    void out(void)
    {   
        // 学号:10010 姓名:hehe 年龄:18 成绩:100
        cout << "学号:" << id << " 姓名:" << name << " 年龄:" << age << " 成绩:" << score << endl;
    }   
private:
    int id; 
    char name[20];
    short age;
    float score; 
};
​
class Student
{
    int id; 
    char name[20];
    short age;
    float score;   
public:
    void in(void)
    {   
        cout << "请输入学生的学号、姓名、年龄、成绩:"; 
        cin >> id >> name >> age >> score;
    }   
    void out(void)
    {   
        // 学号:10010 姓名:hehe 年龄:18 成绩:100
        cout << "学号:" << id << " 姓名:" << name << " 年龄:" << age << " 成绩:" << score << endl;
    } 
};
​
int main(int argc,const char* argv[])
{
    Student stu;
    stu.in();
    stu.out();
    return 0;
}
什么是类对象

使用设计好的类(结构)这种数据类型,定义出的类变量在面向对象编程语言中被称为对象(结构变量),创建类对象的行为也被称为实例化对象。

复制代码
#include <iostream>
using namespace std;
​
class Student
{
    int id; 
    char name[20];
    short age;
    float score;
public:
    void in(void)
    {   
        cout << "请输入学生的学号、姓名、年龄、成绩:"; 
        cin >> id >> name >> age >> score;
    }   
    void out(void)
    {   
        // 学号:10010 姓名:hehe 年龄:18 成绩:100
        cout << "学号:" << id << " 姓名:" << name << " 年龄:" << age << " 成绩:" << score << endl;
    }   
};
​
Student stu; // 在bss内存段上实例化对象
int main(int argc,const char* argv[])
{
    Student stu; // 在stack内存段实例化对象
    Student* stup = new Student; // 在heap内存段实例化对象
}
类的声明与实现分开

如果类的内容不多,一般会选择只定义一个头文件,以类名作为文件名。

复制代码
#ifndef STUDENT_H
#define STUDENT_H
​
class 类名
{
    // 定义成员变量
public:
    // 定义成员函数
};
​
#endif//STUDENT_H

如果类的内容比较多,会选择把类的声明与定义分开,头文件负责类的声明,源文件负责类的实现。

复制代码
#ifndef STUDENT_H
#define STUDENT_H
​
class 类名
{
    // 定义成员变量
public:
    // 声明成员函数
    void 函数名(参数列表);
};
​
#endif//STUDENT_H
复制代码
#include "student.h"
​
void 类名::函数名(参数列表)
{
    
}
相关推荐
L_09075 分钟前
【Algorithm】Day-10
c++·算法·leetcode
大大dxy大大19 分钟前
sklearn-提取字典特征
人工智能·算法·sklearn
15Moonlight24 分钟前
09-MySQL内外连接
数据库·c++·mysql
初学小刘25 分钟前
U-Net系列算法
算法
mit6.82435 分钟前
归并|线段树|树状数组
c++
xlq223221 小时前
10.string(上)
开发语言·c++
Jack电子实验室1 小时前
深入理解C语言函数指针:从基础到实战应用
java·c语言·算法
2501_938773991 小时前
深度对比 ArrayList 与 LinkedList:从底层数据结构到增删查改的性能差异实测
数据结构
hashiqimiya1 小时前
c++的头文件使用
开发语言·c++·算法
panamera122 小时前
C++中vector
开发语言·c++