C++面向对象设计类的核心知识详解总述(1)
C++ 中的类是面向对象编程(OOP)的核心,用于封装数据和操作这些数据的函数。
下面将系统讲解 C++ 中类的核心知识点(包含语法 + 概念 + 示例):
一、类的基本结构
class MyClass {
public:// 构造函数MyClass();// 成员函数void show();private:// 数据成员(属性)int value;
};
- public:公有成员,对外可见
- private:私有成员,仅类内可访问(默认访问权限)
- protected:受保护成员,仅类和其子类可访问
二、构造函数 / 析构函数
构造函数:用于初始化对象
析构函数:对象生命周期结束时调用
class MyClass {
public:MyClass(); // 默认构造函数MyClass(int v); // 带参数构造~MyClass(); // 析构函数
};
MyClass::MyClass() {value = 0;
}MyClass::~MyClass() {std::cout << "Object destroyed" << std::endl;
}
三、this 指针
指向当前对象本身的指针。
class MyClass {
public:void setValue(int value) {this->value = value;}
private:int value;
};
四、成员函数与成员变量
- 成员变量(属性)用于存储数据
- 成员函数用于操作这些数据
支持函数重载(同名不同参数):
class Person {
public:void setAge(int a) { age = a; }void setAge(int a, int b) { age = a + b; }
private:int age;
};
五、类的封装、继承、多态(OOP三大特性)
1. 封装(Encapsulation)
- 通过
private
隐藏实现细节 - 对外提供接口(如
public
成员函数)
2. 继承(Inheritance)
class Animal {
public:void eat() { std::cout << "eat\n"; }
};class Dog : public Animal {
public:void bark() { std::cout << "bark\n"; }
};
Dog
继承了Animal
的成员函数eat()
3. 多态(Polymorphism)
虚函数 + 指针/引用实现运行时多态
class Animal {
public:virtual void speak() { std::cout << "Animal\n"; }
};class Dog : public Animal {
public:void speak() override { std::cout << "Dog\n"; }
};void makeSound(Animal* a) {a->speak(); // 根据实际类型调用
}
六、静态成员与常量成员
静态成员(类共享)
class Counter {
public:static int count;static void show() { std::cout << count; }
};int Counter::count = 0;
常量成员函数(不修改成员变量)
class Test {
public:void print() const; // 不能修改任何成员变量
};
七、友元(friend)
允许某个函数或类访问 private 成员:
class Secret {friend void hacker(Secret&);
private:int data = 42;
};void hacker(Secret& s) {std::cout << s.data;
}
八、运算符重载
可以定义类的“+、=、<<”等行为:
class Vec {
public:Vec(int x) : x(x) {}Vec operator+(const Vec& other) {return Vec(x + other.x);}private:int x;
};
九、类的头文件与实现文件分离
Vec.h
class Vec {
public:Vec(int x);Vec operator+(const Vec& other);
private:int x;
};
Vec.cpp
#include "Vec.h"Vec::Vec(int x) : x(x) {}Vec Vec::operator+(const Vec& other) {return Vec(x + other.x);
}
十、实践例子:一个完整类
#include <iostream>
using namespace std;class Rectangle {
public:Rectangle(int w, int h) : width(w), height(h) {}int area() const { return width * height; }void setHeight(int h) { height = h; }private:int width;int height;
};int main() {Rectangle r(3, 4);cout << "Area: " << r.area() << endl;r.setHeight(5);cout << "Area after resize: " << r.area() << endl;return 0;
}
总结表格
特性 | 关键语法 | 示例 |
---|---|---|
构造函数 | MyClass() | 初始化成员变量 |
析构函数 | ~MyClass() | 资源释放 |
成员函数 | void show() | 类功能 |
成员变量 | int value; | 数据属性 |
继承 | class B : public A | 子类继承父类 |
多态 | virtual , override | 动态调度 |
静态成员 | static int count; | 所有对象共享 |
常量函数 | void func() const; | 保证只读 |
友元 | friend class / function | 访问 private 成员 |
运算符重载 | operator+() | 自定义 +, <<, = 等行为 |