Classes

  • this: 使用实例化的Obj调用类方法时,隐式传入参数this,告诉类方法这个Obj的地址
  • const 修饰成员函数参数列表:常量成员函数,不能修改类成员,也不能调用非const成员函数,对类只读
  • 类的外部定义成员函数:class::funtion。成员函数的声明必须在类中完成
1
2
3
4
5
6
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
units_sold += rhs.units_sold; // this.units_sold += rhs.units_sold
revenus += rhs.revenus;
return *this; // 隐式传入this指针
}
  • 构造函数:C++编译器存在默认构造函数。可自定义构造函数
1
2
3
4
5
6
Sales_data(const std::string &s, unsigned n, double p):bookNo(s), units_sold(n), revenue(p*n) {}

Sales_data::Sales_data(std::istream &is)
{
xxx;
} //在外部定义构造函数

构造函数一般时public的,但是存在例外

  1. 通过静态public函数保证该类只有一个实例时,构造函数只能通过这个静态函数调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Singleton {
private:
// 私有构造函数,禁止外部创建
Singleton() {}

public:
// 静态方法,负责返回唯一实例
static Singleton& getInstance() {
static Singleton instance; // 仅在首次调用时初始化
return instance;
}
};

// 正确:通过静态方法获取实例
Singleton& obj = Singleton::getInstance();

// 错误:无法直接调用私有构造函数
// Singleton obj;
  1. 禁止实例化的工具类

访问控制与封装

public: 外部可访问;private: 外部不可访问
sturct: 默认访问权限是public;class: 默认访问权限是private。希望类所有成员是public时使用struct,否则使用class

友元函数:在类内部声明的可以访问类成员的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

class Rectangle {
private:
int width;
int height;

public:
Rectangle(int w, int h) : width(w), height(h) {}

// 声明友元函数
friend int calculateArea(const Rectangle& rect);
};

// 友元函数定义(注意:不需要加类名::)
int calculateArea(const Rectangle& rect) {
// 可以直接访问私有成员
return rect.width * rect.height;
}

int main() {
Rectangle rect(5, 3);
cout << "矩形面积: " << calculateArea(rect) << endl; // 输出 15
return 0;
}
  • 如果成员是const或者是引用,必须对成员进行初始化。
  • 委托构造函数:使用所属类的其他构造函数构造自己。

类的静态成员

与类本身直接相关,不是与类的哥哥对象关联

声明: static,在外部定义时不需要static,只有声明需要

初始化: 通常不应该在类内进行初始化,但是可以提供const类型的初始值,不过要求静态成员必须是字面值常量类型的constexpr

静态成员和指针可以是不完全类型,而普通成员不行;不完全类型:前向声明,数组类型,递归类型声明