C++class类讲解

文章目录

前言

对于刚开始接触class的初学者们,对这个新概念肯定有一些不理解的地方。我衷心希望本文能够为你答疑解惑。

讲解

我给大家点个重点。区别于函数,class的最后有一个分号结束,这个分号不能省略,否则就会出错。

下面的代码里面的注释会讲 public, privateclass 里该如何定义函数的具体使用方法:

#include <iostream>
using namespace std;

class book // 定义book类
{
public: // 外部可以直接调用调用的函数,变量等
	void get_name(string n);
	void print_book(); // 声明公有继承函数
private: // 只有该class类能够直接调用的函数,变量等
	string name; // 声明私有继承变量
};

// 定义book函数
void book::get_name(string n) { // 定义方式跟class里一样,需要加上类作用域符“::”
	name = n;
}
void book::print_book() {
	cout << "This book's name is " << this->name << '\n';
}
/*
另一种做法是在class里直接定义(本人较为推荐):
class book
{
public:
	void get_name(string n) {
	    name = n;
    }
	void print_book() {
	    cout << "This book's name is " << this->name << '\n';
    }
private: // 只有该class类能够直接调用的函数,变量等
	string name; // 声明私有继承变量
};
*/

int main()
{
	book information; // 声明book类information
	information.get_name("Adventures of Thomas·William"); //使用‘.’调用函数
	information.print_book();
}

小结

总的来说,class类就是让你把一堆函数放在一起,自己成立一个类型。
希望此文能够为你解开困惑!


本文还有诸多不足之处,请读者不吝指教!

<think>好的,用户之前让我介绍了C++的核心知识,现在他想要更深入地了解C++的内容。我需要先回顾一下之前的回答,确保这次讲解不重复,同时补充更多的细节和例子。用户可能是刚开始学习C++,或者希望巩固的相关知识,所以需要结构清晰,分点讲解,并配合代码示例。 首先,用户的问题是关于C++讲解,我需要覆盖的基本结构、构造函数、析构函数、访问控制、静态成员、友元、运算符重载、继承、多态、移动语义和现代特性等。要确保每个部分都有明确的解释和代码示例,帮助用户理解概念。 考虑到用户可能在学习过程中需要实际应用,应该强调实际编程中的常见问题和最佳实践,比如初始化列表的使用、深拷贝与浅拷贝的区别、虚析构函数的重要性等。此外,现代C++特性如override和final关键字、移动构造函数也需要提及,以展示的现代用法。 还需要注意代码格式的正确性,按照之前的系统指令,使用正确的LaTeX格式,独立公式用$$...$$,行内公式用$...$。同时,保持回答结构清晰,分点分段,方便用户逐步理解。 在组织内容时,可能需要先介绍的基本概念,然后逐步深入到更复杂的主题,比如继承和多态,最后讨论现代特性。每个部分都要有代码示例,帮助用户直观理解。同时,注意术语的准确性,比如明确区分成员函数、友元函数、运算符重载等概念。 最后,总结部分需要强调实践的重要性,推荐相关书籍,帮助用户进一步学习。确保整个回答符合用户的需求,既有理论讲解,又有实际示例,帮助用户全面掌握C++的知识。</think>以下是对C++的系统讲解,包含基础语法、关键特性和现代用法,通过代码示例和核心概念说明: --- ### **一、的基本结构** #### 1. 定义 ```cpp class Student { // 名 private: // 访问限定符 std::string name; // 成员变量 int age; public: // 公有接口 // 成员函数声明 void setInfo(const std::string& n, int a); void printInfo() const; // const成员函数 }; // 成员函数定义 void Student::setInfo(const std::string& n, int a) { name = n; age = a; } void Student::printInfo() const { std::cout << name << ", " << age << "岁" << std::endl; } ``` --- ### **二、构造函数与析构函数** #### 1. 构造函数型 | 型 | 作用 | 示例代码 | |-----------------|----------------------------------|-----------------------------------------| | 默认构造函数 | 无参数初始化对象 | `Student() : name(""), age(0) {}` | | 参数化构造函数 | 带参数初始化 | `Student(string n, int a) : name(n), age(a) {}` | | 拷贝构造函数 | 通过已有对象创建新对象(深/浅拷贝)| `Student(const Student& other) { ... }` | | 移动构造函数(C++11) | 高效转移资源 | `Student(Student&& other) noexcept { ... }` | #### 2. 初始化列表 ```cpp // 初始化列表优先于赋值操作 Student::Student(const std::string& n, int a) : name(n), // 直接初始化成员变量 age(a) { // 避免默认构造+赋值的开销 } ``` #### 3. 析构函数 ```cpp class FileHandler { public: FileHandler(const char* filename) { file = fopen(filename, "r"); } ~FileHandler() { if(file) fclose(file); // 确保资源释放 } private: FILE* file; }; ``` --- ### **三、访问控制与封装** | 访问限定符 | 作用范围 | |------------|--------------------------------------| | `public` | 外可直接访问 | | `private` | 仅内和友元访问(默认访问级别) | | `protected`| 内、派生和友元访问 | #### 示例:封装的典型场景 ```cpp class BankAccount { private: double balance; // 隐藏实现细节 public: void deposit(double amount) { // 提供安全接口 if(amount > 0) balance += amount; } double getBalance() const { return balance; } }; ``` --- ### **四、静态成员** #### 1. 静态变量 ```cpp class Counter { public: static int count; // 声明静态成员 Counter() { ++count; } ~Counter() { --count; } }; int Counter::count = 0; // 外定义并初始化 // 使用:cout << Counter::count; // 直接通过访问 ``` #### 2. 静态函数 ```cpp class MathUtils { public: static double PI() { return 3.1415926; } // 不操作非静态成员 }; // 调用:double pi = MathUtils::PI(); ``` --- ### **五、友元(Friend)** #### 1. 友元函数 ```cpp class Box { private: double width; public: friend void printWidth(Box box); // 授权访问私有成员 }; void printWidth(Box box) { std::cout << "Width: " << box.width << std::endl; } ``` #### 2. 友元 ```cpp class Storage { private: int secretKey; friend class SecurityCheck; // 授权整个访问 }; class SecurityCheck { public: static bool validate(const Storage& s) { return s.secretKey == 123456; // 直接访问私有成员 } }; ``` --- ### **六、运算符重载** #### 1. 成员函数形式 ```cpp class Vector2D { public: double x, y; Vector2D operator+(const Vector2D& other) const { return Vector2D(x + other.x, y + other.y); } }; ``` #### 2. 全局函数形式(需声明为友元) ```cpp class Vector2D { friend Vector2D operator*(double scalar, const Vector2D& vec); }; Vector2D operator*(double scalar, const Vector2D& vec) { return Vector2D(scalar * vec.x, scalar * vec.y); } ``` --- ### **七、继承与多态** #### 1. 继承型 | 继承方式 | 基`public`成员变为 | 基`protected`成员变为 | |------------|----------------------|-------------------------| | `public` | 派生的`public` | 派生的`protected` | | `protected` | 派生的`protected` | 派生的`protected` | | `private` | 派生的`private` | 派生的`private` | #### 2. 虚函数与多态 ```cpp class Animal { public: virtual void makeSound() const { // 虚函数 std::cout << "Some animal sound" << std::endl; } virtual ~Animal() {} // 虚析构函数 }; class Dog : public Animal { public: void makeSound() const override { // C++11明确override std::cout << "Woof!" << std::endl; } }; // 使用多态 Animal* animal = new Dog(); animal->makeSound(); // 输出 Woof! delete animal; ``` --- ### **八、现代C++特性** #### 1. `default`和`delete`函数 ```cpp class NonCopyable { public: NonCopyable() = default; NonCopyable(const NonCopyable&) = delete; // 禁止拷贝 }; ``` #### 2. 移动语义(C++11) ```cpp class Buffer { public: // 移动构造函数 Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) { other.data = nullptr; // 转移所有权 other.size = 0; } private: int* data; size_t size; }; ``` --- ### **九、最佳实践** 1. **遵循RAII原则**:在构造函数中获取资源,在析构函数中释放 2. **优先使用初始化列表**:避免成员变量的默认初始化+赋值操作 3. **虚析构函数规则**:基有虚函数时,必须声明虚析构函数 4. **优先使用`override`关键字**(C++11):明确表示覆盖基虚函数 5. **慎用友元**:破坏封装性,仅在必要时使用 --- ### **十、关系图示** ``` 继承 ↗ ↖ 继承 组合 ↘ ↙ 聚合 // 示例: class Engine {}; // 组合:Car "拥有" Engine class Wheel {}; // 聚合:Car "包含" Wheel(可独立存在) class Vehicle {}; // 继承:Car 是 Vehicle class Car : public Vehicle { private: Engine engine; // 组合关系 std::vector<Wheel> wheels;// 聚合关系 }; ``` --- 通过系统掌握这些相关概念,可以设计出高内聚、低耦合的C++程序。建议结合《Effective C++》和《C++ Coding Standards》等书籍深入理解设计原则。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值