程序设计与算法(三)C++面向对象程序设计 第三周 相关笔记
1、this指针的运用
指向当前函数作用类的指针
相当于翻译为C语言,r.run() = run(test * this)

#include<bits/stdc++.h> using namespace std; class test{ private: double real,imag; public: test(double r,double i):real(r),imag(i) {} void add_one(){ this->real ++; } void get_(){ cout<<this->real<<" "<<this->imag<<endl; } }; int main(){ test a(1,2); a.add_one(); a.get_(); }

#include<bits/stdc++.h> using namespace std; class test{ private: double real,imag; public: test(double r,double i):real(r),imag(i) void out(){ cout<<"Hello"<<endl; } }; int main(){ test* p = NULL; p->out(); }
2、静态成员
分为静态成员函数,静态成员变量
相当于全局函数,全局变量
定义静态成员变量需要先说明
int CRectangle::nTotleArea = 0;
静态成员函数内不能访问非静态变量与非静态函数

#include<bits/stdc++.h> using namespace std; class Rectangle{ private: int w,h; static int total_area; static int total_number; public: Rectangle(int _w,int _h){ w = _w; h = _h; total_area += w*h; total_number++; } Rectangle(Rectangle& r){ w = r.w; h = r.h; total_area += w*h; total_number++; } ~Rectangle(){ total_area -= w*h; total_number--; } static void out(){ cout<<total_number<<" "<<total_area<<endl; } }; int Rectangle::total_number = 0; int Rectangle::total_area = 0; int main(){ Rectangle r1(1,2); Rectangle* r2 = new Rectangle(2,4); Rectangle r3(2,3); Rectangle::out(); delete r2; Rectangle::out(); Rectangle r4 = r1; Rectangle::out(); return 0; } 输出: 3 16 2 8 3 10
添加构造函数后默认无参构造函数消失
但是复制构造函数依然在
3、成员对象与封闭类
有成员对象的类叫做封闭类
封闭类的构造函数与析构函数的执行顺序相反
构造函数都是先生产成员对象,在操作封闭类
析构函数先操作封闭类 先操作成员对象

#include<bits/stdc++.h> using namespace std; class tyre{ public: tyre(){ cout<<"tyre constructor"<<endl; } ~tyre(){ cout<<"tyre destructor"<<endl; } }; class engine{ public: engine(){ cout<<"engine constructor"<<endl; } ~engine(){ cout<<"engine destructor"<<endl; } }; class Car{ tyre t; engine e; public: Car(){ cout<<"car constructor"<<endl; } ~Car(){ cout<<"car destructor"<<endl; } }; int main(){ Car c; return 0; } 输出: tyre constructor engine constructor car constructor car destructor engine destructor tyre destructor
封闭类的复制构造函数还是调用其成员的对象的复制构造函数
pass
4、友元 friend
一个类友元函数可以访问该类的私有成员
一个类友元类可以访问该类的私有成员

#include<bits/stdc++.h> using namespace std; class Car{ int a = 1,b = 2; public: friend void get_(Car c); }; //改成指针也可 //class 也行 void get_(Car c){ cout<<c.a<<" "<<c.b<<endl; } int main(){ Car c; get_(c); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人