1. C++类与对象高级特性解析
在掌握了C++类和对象的基础概念后,我们需要深入探讨其高级特性。面向对象编程的核心在于封装、继承和多态,而C++通过类和对象提供了完整的实现机制。
1.1 构造函数与析构函数进阶
构造函数和析构函数是类中最重要的特殊成员函数。构造函数在对象创建时自动调用,而析构函数在对象销毁时自动执行。
cpp复制class Person {
public:
// 默认构造函数
Person() {
cout << "默认构造函数被调用" << endl;
}
// 带参数的构造函数
Person(string name, int age) : name_(name), age_(age) {
cout << "带参数构造函数被调用" << endl;
}
// 拷贝构造函数
Person(const Person& other) {
name_ = other.name_;
age_ = other.age_;
cout << "拷贝构造函数被调用" << endl;
}
// 析构函数
~Person() {
cout << "析构函数被调用" << endl;
}
private:
string name_;
int age_;
};
注意:当类中包含指针成员时,必须实现拷贝构造函数和赋值运算符重载,避免浅拷贝问题。
1.2 静态成员与友元
静态成员属于类本身而非对象,所有对象共享同一份静态成员。友元则可以突破封装限制,访问类的私有成员。
cpp复制class Account {
public:
Account(double balance) : balance_(balance) {
totalAccounts++;
totalBalance += balance;
}
~Account() {
totalAccounts--;
totalBalance -= balance_;
}
static int getTotalAccounts() {
return totalAccounts;
}
static double getTotalBalance() {
return totalBalance;
}
friend void printAccountInfo(const Account& acc);
private:
double balance_;
static int totalAccounts;
static double totalBalance;
};
// 静态成员初始化
int Account::totalAccounts = 0;
double Account::totalBalance = 0.0;
// 友元函数实现
void printAccountInfo(const Account& acc) {
cout << "账户余额: " << acc.balance_ << endl;
}
2. 运算符重载与类型转换
C++允许重载大多数运算符,使得自定义类型也能像内置类型一样使用运算符。
2.1 基本运算符重载
cpp复制class Complex {
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 重载+运算符
Complex operator+(const Complex& rhs) const {
return Complex(real + rhs.real, imag + rhs.imag);
}
// 重载-运算符
Complex operator-(const Complex& rhs) const {
return Complex(real - rhs.real, imag - rhs.imag);
}
// 重载<<运算符(通常声明为友元)
friend ostream& operator<<(ostream& os, const Complex& c);
private:
double real, imag;
};
ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << ")";
return os;
}
2.2 类型转换运算符
C++允许定义类型转换运算符,实现自定义类型与其他类型之间的转换。
cpp复制class Distance {
public:
Distance(double meters = 0.0) : meters_(meters) {}
// 转换为double类型
operator double() const {
return meters_;
}
// 转换为字符串
operator string() const {
return to_string(meters_) + " meters";
}
private:
double meters_;
};
3. 继承与多态
继承是面向对象编程的重要特性,允许创建基于现有类的新类。多态则允许通过基类指针或引用调用派生类的函数。
3.1 继承基础
cpp复制class Shape {
public:
virtual double area() const = 0; // 纯虚函数
virtual ~Shape() {} // 虚析构函数
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
private:
double radius;
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
private:
double width, height;
};
3.2 多态实现
多态通过虚函数实现,运行时根据对象的实际类型调用相应的函数。
cpp复制void printArea(const Shape& shape) {
cout << "面积: " << shape.area() << endl;
}
int main() {
Circle c(5.0);
Rectangle r(4.0, 6.0);
printArea(c); // 调用Circle的area()
printArea(r); // 调用Rectangle的area()
return 0;
}
提示:基类析构函数应该声明为虚函数,确保通过基类指针删除派生类对象时能正确调用派生类的析构函数。
4. 模板与泛型编程
C++模板支持泛型编程,允许编写与类型无关的代码。
