当前位置:   article > 正文

C++类和对象中的const成员,取地址及const取地址操作符重载_通过同一类创建的对象,其常数据成员(const)使用相同的地址

通过同一类创建的对象,其常数据成员(const)使用相同的地址

const修饰类的成员函数

将const修饰的类成员函数称之为const成员函数.
const修饰类的成员函数, 实际上修饰的是该成员函数隐含的this指针, 这表明在该成员函数中不能对类的任何成员进行修改.

看下面这段代码:

#include <iostream>

using namespace std;

class Date
{
	int m_year;
	int m_month;
	int m_day;
public:

	void display()
	{
		cout << "display ()" << endl;        
		cout << "year:" << m_year << endl;        
		cout << "month:" << m_month << endl;
		cout << "day:" << m_day << endl << endl;
	}

	void display() const
	{
		cout << "display () const" << endl;
		cout << "year:" << m_year << endl;
		cout << "month:" << m_month << endl;
		cout << "day:" << m_day << endl << endl;
	}
};

int main()
{
	Date d1;
	d1.display();

	const Date d2;
	d2.display();

	system("pause");
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

总结

  1. const对象可以调用其它的const函数
  2. 非const对象可以调用非const成员函数和const成员函数
  3. const成员函数内部可以调用其他的const成员函数
  4. 非const成员函数内可以调用其它的const成员函数和非const成员函数

取地址及const取地址操作符重载

这两个默认成员函数一般不用重定义, 编译器会默认生成

class Date
{
	int m_year;
	int m_month;
	int m_day;
public:
	Date * operator &()
	{
		return this;
	}
	const Date * operator &() const
	{	
		return this;
	}
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

这两个运算符一般不需要重载, 使用编译器生成的默认取地址的重载即可, 只有特殊情况, 才需要重载, 比如不想让其他用户获取到指定内容.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/608181
推荐阅读
相关标签
  

闽ICP备14008679号