十一.C++ 类 -- 面向对象思想

类的定义

class/struct 类名 : 继承方式,基类...{

类名(行参表):成员变量(初值)...{

函数体;

}

~类名(void){

函数体;

}

返回类型 函数名 (形参表) 常属性 异常说明{

函数体;

}

数据类型 变量名;

}

访问控制限定符

  • public 共有成员 谁都可以访问

  • private 私有成员 只有自己可以访问

  • protected 保护成员,只有自己和子类可以访问

成员变量

成员变量在对象中存着

成员函数

成员函数在代码端储存

cpp 复制代码
class Human
{
public:
    Human();
    ~Human();
    
	void setInfo(int age,const char* name)
	{
    	m_age = age;
    	strcpy_s(m_name, name);

	};

	void getInfo()
	{
    	cout << "age = " << m_age << " name = " << m_name << endl;
	};

private:
	 int age;
 	 char name[256];
};

Human::Human()
{
}

Human::~Human()
{
}

int main()
{
     Human h;

 	h.setInfo(20, "wyd");

 	h.getInfo();   // age = 20 name = wyd
}

This指针

C++成员函数模型

  • 类的每个成员函数(除静态成员函数外),都有一个隐藏的指针型参数,形参名为this,指向调用该成员函数的对象,这就是this指针

  • 在类的成员函数中(除静态成员函数外),对所有成员的访问,都是通过this指针进行的

cpp 复制代码
void setInfo(/* 隐藏一个 Human* this指针 */int age,const char* name)
	{
    	m_age = age;
    	strcpy_s(m_name, name);

	};

void getInfo(/* Human* this */)
	{
    	cout << "age = " << m_age << " name = " << m_name << endl;
	};

可以用另外一种写法证明:

cpp 复制代码
void setInfo(/* 隐藏一个 Human* this指针 */int age,const char* name)
 {
     this->age = age;
     strcpy_s(this->name, name);

 };

 void getInfo(/* Human* this */)
 {
     cout << "age = " << this->age << " name = " << this->name << endl;
 };
this指针的应用(必须自己使用this的情况)
  • 多数情况下,程序并不需要显式的使用指针this

  • 有时为了方便,将类的成员变量与该成员函数的参数相同标识符,这时在成员函数内部,可以通过this指针将两者加以区分

cpp 复制代码
void setInfo(int age,const char* name)
 {
     this->age = age;
     strcpy_s(this->name, name);

 };

 void getInfo()
 {
     cout << "age = " << this->age << " name = " << this->name << endl;
 };


private:
	 int age;
 	 char name[256];
};
  • 返回基于this指针的自引用,以支持串连调用
cpp 复制代码
Human& increment()
{
    ++age;

    return *this;
}

h.increment();

h.getInfo();   // age = 21 name = wyd
  • 将this指针作为函数的参数,以实现对象交互
相关推荐
傻啦嘿哟5 小时前
某招聘平台爬虫:爬取招聘岗位数据,分析各城市薪资水平
开发语言·爬虫·python
2501_933670795 小时前
2026秋招量化分析岗技能栈:Python、SQL、统计建模、回测项目怎么准备
开发语言·python·sql
李少兄6 小时前
JavaScript 数据类型完全指南
开发语言·javascript·ecmascript
码匠许师傅6 小时前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
Seoyoneh6 小时前
Agentic Workflow编排架构:云客服从“被动响应”迈向“主动执行”的技术实现
java·开发语言·架构
啦啦啦啦啦zzzz6 小时前
Logger的组装(c++20)
c++·算法·c++20
Tangyuewei6 小时前
Java 写 Agent:模型只是组件
java·开发语言
小玮看世界7 小时前
[Python]从合并区间到传感器融合区:合并区间在传感器区域融合的实际落地
开发语言·python
繁星蓝雨8 小时前
C++的设计与演进大纲(如何从C语言一步步成长为C++)
c语言·开发语言·c++·c++历史·c++演进
Evand J8 小时前
【MATLAB例程,图像降噪滤波9】自适应维纳滑动窗口滤波(Wiener)图像降噪、方法对比,有中文注释
开发语言·图像处理·计算机视觉·matlab·滑动窗口·滤波·降噪