<think>我们正在处理一个关于C++编程的问题,用户要求提供关于多个主题的示例代码和解答。主题包括:
1. 抽象类与纯虚函数示例代码
2. 函数模板实现
3. 类模板与可变参数模板
4. 折叠表达式应用
5. 多态与容器使用
6. 可变参数模板函数递归实现
7. 类模板特化方法
我们将逐一解答这些主题,并给出相应的代码示例。注意,由于用户要求的是参考答案,我们将提供简洁但完整的示例。
### 1. 抽象类与纯虚函数示例代码
抽象类通过纯虚函数定义,不能实例化,只能被继承。子类必须实现纯虚函数。
```cpp
#include <iostream>
using namespace std;
// 抽象类
class Shape {
public:
// 纯虚函数
virtual double area() const = 0;
virtual void display() const = 0;
virtual ~Shape() {}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
void display() const override {
cout << "Circle with radius " << radius << ", area: " << area() << endl;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
void display() const override {
cout << "Rectangle " << width << "x" << height << ", area: " << area() << endl;
}
};
int main() {
Shape* shapes[] = { new Circle(5), new Rectangle(4, 6) };
for (Shape* s : shapes) {
s->display();
}
// 释放内存
for (Shape* s : shapes) {
delete s;
}
return 0;
}
```
### 2. 函数模板实现
函数模板允许编写与类型无关的代码。
```cpp
#include <iostream>
using namespace std;
// 函数模板:求两个数的最大值
template <typename T>
T max(T a, T b) {
return a > b ? a : b;
}
int main() {
cout << max(3, 5) << endl; // 输出5
cout << max(3.14, 2.71) << endl; // 输出3.14
cout << max('a', 'z') << endl; // 输出z
return 0;
}
```
### 3. 类模板与可变参数模板
类模板可以接受可变数量的模板参数(可变参数模板)。
```cpp
#include <iostream>
using namespace std;
// 类模板:元组(可变参数模板)
template <typename... Args>
class Tuple;
// 递归终止:空元组
template <>
class Tuple<> {};
// 递归定义
template <typename Head, typename... Tail>
class Tuple<Head, Tail...> : private Tuple<Tail...> {
public:
Tuple(Head h, Tail... t) : Tuple<Tail...>(t...), head(h) {}
Head headValue() const { return head; }
Tuple<Tail...>& tail() { return *this; }
private:
Head head;
};
int main() {
Tuple<int, double, string> t(1, 2.3, "hello");
cout << t.headValue() << endl; // 1
cout << t.tail().headValue() << endl; // 2.3
cout << t.tail().tail().headValue() << endl; // hello
return 0;
}
```
### 4. 折叠表达式应用
折叠表达式(C++17)简化可变参数模板的展开。
```cpp
#include <iostream>
using namespace std;
// 折叠表达式:求和
template <typename... Args>
auto sum(Args... args) {
return (args + ...); // 一元右折叠
}
// 折叠表达式:打印所有参数
template <typename... Args>
void printAll(Args... args) {
(cout << ... << args) << endl; // 二元左折叠
}
int main() {
cout << sum(1, 2, 3, 4, 5) << endl; // 15
printAll(1, " ", 2.3, " ", "hello"); // 输出:1 2.3 hello
return 0;
}
```
### 5. 多态与容器使用
使用多态对象时,通常需要存储指针(或智能指针)在容器中。
```cpp
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
// 抽象类
class Animal {
public:
virtual void speak() const = 0;
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void speak() const override {
cout << "Woof!" << endl;
}
};
class Cat : public Animal {
public:
void speak() const override {
cout << "Meow!" << endl;
}
};
int main() {
vector<unique_ptr<Animal>> animals;
animals.push_back(make_unique<Dog>());
animals.push_back(make_unique<Cat>());
for (const auto& animal : animals) {
animal->speak();
}
return 0;
}
```
### 6. 可变参数模板函数递归实现
递归展开可变参数包是经典方法。
```cpp
#include <iostream>
using namespace std;
// 递归终止函数
void print() {
cout << endl;
}
// 递归展开
template <typename T, typename... Args>
void print(T first, Args... args) {
cout << first << " ";
print(args...);
}
int main() {
print(1, 2.5, "three", '4'); // 输出:1 2.5 three 4
return 0;
}
```
### 7. 类模板特化方法
类模板特化允许为特定类型提供定制实现。
```cpp
#include <iostream>
using namespace std;
// 主模板
template <typename T>
class Box {
public:
void display() {
cout << "General Box" << endl;
}
};
// 全特化:针对int类型
template <>
class Box<int> {
public:
void display() {
cout << "Box for integers" << endl;
}
};
// 部分特化:针对指针类型
template <typename T>
class Box<T*> {
public:
void display() {
cout << "Box for pointers" << endl;
}
};
int main() {
Box<double> b1;
b1.display(); // General Box
Box<int> b2;
b2.display(); // Box for integers
Box<int*> b3;
b3.display(); // Box for pointers
return 0;
}
```
以上示例代码涵盖了用户要求的各个主题。注意,在实际编程中,可能需要根据具体需求调整代码。
§§相关问题§§
1. 纯虚函数在抽象类中有什么作用?
2. 函数模板和类模板的主要区别是什么?
3. 可变参数模板在C++11中如何工作?
4. 折叠表达式在C++17中有哪些应用场景?
5. 在多态中使用容器时,为什么通常使用指针或智能指针?
6. 递归展开可变参数包时,为什么需要终止函数?
7. 类模板特化有哪几种类型?它们分别适用于什么情况?</think>### C++ 抽象类与纯虚函数示例代码
抽象类通过纯虚函数定义接口,无法实例化,只能被继承。子类必须实现纯虚函数:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 抽象类
class Shape {
public:
virtual double area() const = 0; // 纯虚函数
virtual void draw() const = 0; // 纯虚函数
virtual ~Shape() = default; // 虚析构函数
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
void draw() const override {
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
void draw() const override {
cout << "Drawing Rectangle" << endl;
}
};
int main() {
vector<Shape*> shapes = { new Circle(5), new Rectangle(4, 6) };
for (auto s : shapes) {
s->draw();
cout << "Area: " << s->area() << endl;
delete s;
}
return 0;
}
```
> **输出**:
> Drawing Circle
> Area: 78.5397
> Drawing Rectangle
> Area: 24
---
### 函数模板实现
函数模板支持泛型编程,自动推导参数类型:
```cpp
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << max(10, 20) << endl; // 输出 20
cout << max(3.14, 2.71) << endl; // 输出 3.14
cout << max('a', 'z') << endl; // 输出 z
}
```
---
### 类模板与可变参数模板
可变参数模板支持任意数量和类型的参数:
```cpp
template <typename... Args>
class Tuple {};
template <typename Head, typename... Tail>
class Tuple<Head, Tail...> : public Tuple<Tail...> {
Head data;
public:
Tuple(Head h, Tail... t) : Tuple<Tail...>(t...), data(h) {}
Head getHead() const { return data; }
};
int main() {
Tuple<int, double, string> t(42, 3.14, "Hello");
cout << t.getHead() << endl; // 输出 42
}
```
---
### 折叠表达式应用(C++17)
简化可变参数包的展开:
```cpp
template <typename... Args>
auto sum(Args... args) {
return (args + ...); // 一元右折叠
}
template <typename... Args>
void printAll(Args... args) {
(cout << ... << args) << endl; // 二元左折叠
}
int main() {
cout << sum(1, 2, 3, 4) << endl; // 输出 10
printAll("A", "B", 123); // 输出 AB123
}
```
---
### 多态与容器使用
容器存储基类指针实现多态:
```cpp
int main() {
vector<unique_ptr<Shape>> shapes;
shapes.push_back(make_unique<Circle>(3));
shapes.push_back(make_unique<Rectangle>(4, 5));
for (auto& s : shapes) {
s->draw();
cout << "Area: " << s->area() << endl;
}
}
```
> **关键点**:
> - 使用 `unique_ptr` 自动管理内存
> - 通过基类指针调用子类方法
---
### 可变参数模板函数递归实现
递归展开参数包:
```cpp
// 递归终止函数
void print() { cout << endl; }
template <typename T, typename... Args>
void print(T first, Args... args) {
cout << first << " ";
print(args...); // 递归调用
}
int main() {
print(1, 2.5, "three", '4'); // 输出: 1 2.5 three 4
}
```
---
### 类模板特化方法
针对特定类型定制实现:
```cpp
// 主模板
template <typename T>
class Printer {
public:
void print(T val) { cout << "Generic: " << val << endl; }
};
// 全特化:针对 int 类型
template <>
class Printer<int> {
public:
void print(int val) { cout << "Integer: " << val << endl; }
};
// 部分特化:针对指针类型
template <typename T>
class Printer<T*> {
public:
void print(T* ptr) { cout << "Pointer: " << *ptr << endl; }
};
int main() {
Printer<double> p1; p1.print(3.14); // Generic: 3.14
Printer<int> p2; p2.print(42); // Integer: 42
int x = 100;
Printer<int*> p3; p3.print(&x); // Pointer: 100
}
```
---
### 综合应用:多态 + 模板 + 容器
```cpp
template <typename... Args>
void processShapes(Args... shapes) {
vector<Shape*> vec = {shapes...};
for (auto s : vec) {
s->draw();
cout << "Area: " << s->area() << endl;
}
}
int main() {
Circle c(2);
Rectangle r(3, 4);
processShapes(&c, &r);
}
```