首页 > 其他分享 >Const修饰类成员函数

Const修饰类成员函数

时间:2022-09-25 11:45:46浏览次数:53  
标签:const 函数 int 成员 SimpleConst 修饰 Const include 指针

主要说明const 类成员函数调用方式 以及this指针对应变化

SimpleConst.h
#pragma once
class A
{
public:
	int a;
	int b;
	const int c;
	
	A(int i, int j, int t);

	//const 成员函数
	void PrintSum() const;


	void AddNum();
};
SimpleConst.cpp

#include "SimpleConst.h"
#include <iostream>
using namespace std;

A::A(int i, int j, int t):
	a(i),b(j),c(t)
{
	cout << "Constr" << endl;
}

void A::PrintSum() const
{
	cout << "a:"<<a << " b" << b << " c" << c <<endl;
}


void A::AddNum()
{
	a = a * 2;
	b = b * 2;

	cout << "Add Num()" << a << b << endl;
}
main.cpp 

#include <iostream>
#include "SimpleConst.h"
int main()
{
	class A* ptr_a = new A(5,7,6);
	//非const 类指针下的 this 指针 A * const this
	//非const 类指针 成员可以调用普通成员函数/const 成员函数
	ptr_a->PrintSum();
	ptr_a->AddNum();


	const class A* c_prt_a = new A(44, 5, 6);
	c_prt_a->PrintSum();
	//const 类指针下的 this 指针 const A * const this 
	//const 类指针/引用 仅能调用const 成员函数
	
}

标签:const,函数,int,成员,SimpleConst,修饰,Const,include,指针
From: https://www.cnblogs.com/zsymdbk/p/16727535.html

相关文章