C++实现一个复杂的类,包括所有C++的知识点
时间: 2023-07-11 08:03:53 浏览: 85
实现一个C++类
一个复杂的类可以包括以下C++知识点:
1. 构造函数和析构函数
2. 静态成员变量和静态成员函数
3. 友元函数和友元类
4. 继承和多态
5. 运算符重载
6. 模板和泛型编程
7. 异常处理
8. RAII(资源获取即初始化)
下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person {
public:
// 构造函数
Person(string name, int age) : m_name(name), m_age(age) {
cout << "Person constructor called" << endl;
}
// 析构函数
~Person() {
cout << "Person destructor called" << endl;
}
// 静态成员变量和静态成员函数
static int s_count;
static void s_func() {
cout << "Static function called" << endl;
}
// 友元函数和友元类
friend void friend_func(Person& p) {
cout << "Friend function called, name: " << p.m_name << endl;
}
friend class FriendClass;
// 继承和多态
virtual void virtual_func() {
cout << "Person virtual function called" << endl;
}
// 运算符重载
bool operator<(const Person& other) const {
return m_age < other.m_age;
}
// 模板和泛型编程
template <typename T>
void template_func(vector<T>& vec) {
for (auto& v : vec) {
cout << v << " ";
}
cout << endl;
}
// 异常处理
void throw_exception() {
throw runtime_error("Exception thrown");
}
// RAII(资源获取即初始化)
class Resource {
public:
Resource() {
cout << "Resource acquired" << endl;
}
~Resource() {
cout << "Resource released" << endl;
}
};
private:
string m_name;
int m_age;
};
// 静态成员变量初始化
int Person::s_count = 0;
// 继承和多态
class Student : public Person {
public:
Student(string name, int age, string school) : Person(name, age), m_school(school) {
cout << "Student constructor called" << endl;
}
~Student() {
cout << "Student destructor called" << endl;
}
void virtual_func() override {
cout << "Student virtual function called" << endl;
}
private:
string m_school;
};
// 友元类
class FriendClass {
public:
void friend_class_func(Person& p) {
cout << "Friend class function called, age: " << p.m_age << endl;
}
};
int main() {
// 构造函数和析构函数
Person p("Tom", 20);
// 静态成员变量和静态成员函数
Person::s_count = 10;
Person::s_func();
// 友元函数和友元类
friend_func(p);
FriendClass fc;
fc.friend_class_func(p);
// 继承和多态
Person* ptr = new Student("Jerry", 18, "MIT");
ptr->virtual_func();
delete ptr;
// 运算符重载
vector<Person> vec{Person("A", 10), Person("B", 30), Person("C", 20)};
sort(vec.begin(), vec.end());
for (auto& v : vec) {
cout << v.m_name << " ";
}
cout << endl;
// 模板和泛型编程
vector<int> int_vec{1, 2, 3};
vector<string> str_vec{"hello", "world"};
p.template_func<int>(int_vec);
p.template_func<string>(str_vec);
// 异常处理
try {
p.throw_exception();
} catch (const exception& e) {
cout << e.what() << endl;
}
// RAII(资源获取即初始化)
{
Person::Resource res;
}
return 0;
}
```
阅读全文