<C++>15.this指针

本文介绍了C++中this指针的概念及其应用场景。通过实例演示了如何使用this指针来操作对象成员,并展示了this指针指向对象地址的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

15.this指针

一、概述


1、概念:

this指针是隐含与每一个成员函数中的特殊指针。它指向正操作该成员函数的对象。


2、this指针的产生:

当对象调用成员函数时,程序先将对象的地址赋予this指针,然后调用成员函数。

 

二、应用举例

/* this_ptr.c */

#include <iostream>

using namespace std;

class A
{
private:
	int n;
	
public:
	void set_value(int x)
	{
		this->n = x;
		cout<<"this指针指向的地址: "<<this<<endl;
	}
	void print_n()
	{
		cout<<"对象的n值:"<<n<<endl;
	}
};

int main (int argc, char *argv[])
{
	A a;
	cout<<"a的内存地址:"<<&a<<endl;
	a.set_value(3);
	a.print_n();
	
	return 0;
}


结果:

 

可以看到this指针指向的地址就是调用成员函数的对象的地址,this->n等价于a.n


题目1:抽象类与纯虚函数 设计一个抽象类Shape,包含: 纯虚函数 virtual double area() const = 0 纯虚函数 virtual void print() const = 0 创建派生类CircleRectangle实现这些函数,要求: Circle需包含半径成员,area()计算圆面积 Rectangle需包含长宽成员,print()输出形状信息 C++ // 示例代码框架 class Shape { /* 抽象类声明 */ }; class Circle : public Shape { /* 实现 */ }; class Rectangle : public Shape { /* 实现 */ }; 考察点:抽象类定义、纯虚函数实现、多态调用1 题目2:函数模板 编写通用函数模板getMax: 接受两个相同类型的参数,返回较大值 特化版本:对char*类型使用strcmp比较 C++ template <typename T> T getMax(T a, T b) { /* 通用实现 */ } template <> const char* getMax<const char*>(const char* a, const char* b) { /* 特化实现 */ } 考察点:函数模板、模板特化 题目3:类模板与递归可变参数 实现类模板Tuple: 支持任意数量类型(如Tuple<int, string, double>) 使用递归继承存储元素 添加get<Index>()方法获取元素 C++ template <typename... Ts> class Tuple; // 主模板声明 template <typename Head, typename... Tail> class Tuple<Head, Tail...> : private Tuple<Tail...> { /* 递归继承 */ }; 考察点:类模板、可变参数模板、递归继承 题目4:折叠表达式(C++17) 用折叠表达式实现函数模板sum: 计算任意数量参数的加(支持int, double等) 要求单行实现 C++ template <typename... Args> auto sum(Args... args) { return (args + ...); // 折叠表达式 } 考察点:折叠表达式、可变参数模板 题目5:多态与容器 创建抽象类Animal: 纯虚函数 virtual void speak() const = 0 派生类Dog、Cat实现speak()(分别输出"Woof"、“Meow”) 在main()中用vector<Animal*>存储不同动物对象,遍历调用speak() 考察点:多态、容器与抽象类结合 题目6:可变参数模板函数 实现编译时递归的printAll函数: 递归终止条件:无参数时返回 递归步骤:打印第一个参数,处理剩余参数 C++ void printAll() {} // 终止递归 template <typename T, typename... Args> void printAll(T first, Args... rest) { std::cout << first << " "; printAll(rest...); } 考察点:可变参数模板、递归展开 题目7:类模板特化 设计泛型容器Box<T>: 通用版本:存储T类型元素,提供put()get()方法 全特化版本:Box<void>禁止实例化(静态断言报错) 偏特化版本:Box<T*>管理指针,自动释放内存 考察点:类模板特化、偏特化 参考答案要点 抽象类通过纯虚函数强制派生类实现接口1 模板在编译时实例化,避免运行时开销 可变参数模板递归需定义终止条件 多态通过基类指针/引用调用派生类方法 折叠表达式(C++17)简化可变参数操作。帮我把上面这几道题的答案显示
最新发布
07-28
<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); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值