C++语言—类的const成员

const修饰普通变量:
在C++中,const修饰的变量已经为一个常量,具有宏的属性,即在编译期间,编译器会将const所修饰的变量进行替换。
const修饰类成员:

 const修饰类成员变量时,该成员变量必须在构造函数的初始化列表中初始化

 const修饰类成员函数,实际修饰该成员函数隐含的this指针指向的内容,该成员函数中不能对类的任何成员进行修改

class Date
{
public:
	Date(int year,int month,int day)
		:_year(year)  //_year只能在此处初始化
		,_month(month)
		,_day(day)
	{}
	void show() const
	{
//		this->_day = 2018;  //函数体内无法改变类成员变量
		cout << _year<<"-"<< _month<<"-"<< _day << endl;
	}
private:
	const int _year;
	int _month;
	int _day;
};

 在const修饰的成员函数可能需要对类的某个成员变量进行修改,该成员变量只需被mutable关键字修饰即可

来看看以下几种场景:

1. 和const对象可以调用非const成员函数const成员函数吗?

2. 非const对象可以调用非const成员函数和const成员函数吗?

3. const成员函数内可以调用其它的const成员函数和非const成员函数吗?

4. 非const成员函数内可以调用其它的const成员函数和非const成员函数吗?

通过以下代码及其中的注释理解这里的问题是很容易的:

class Date
{
public:
	Date(int year,int month,int day)
		:_year(year)
		,_month(month)
		,_day(day)
	{}

	void Displayinfo()  //非const函数
	{
		showinfo();  //非const成员函数可以调用const成员函数
		cout << _year << "-" << _month << "-" << _day << endl;
	}

	void showinfo() const  //const函数
	{
//		Displayinfo();  //const成员函数不可以调用非const成员函数
		cout << _year<<"-"<< _month<<"-"<< _day << endl;
	}
private:
	const int _year;
	int _month;
	int _day;
};

void test1()
{
	const Date d1(2000,1,1);  //const对象
	Date d2(2018, 9, 6);  //非const对象

//	d1.Displayinfo();  //const对象不可以调用非const成员函数
	d1.showinfo();   //const对象可以调用const成员函数

	d2.Displayinfo();  //非const对象可以调用非const成员函数
	d2.showinfo();  //非const对象可以调用const成员函数
}

 关于类的const成员这块就说这么多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C 语言中,并没有直接的的概念,因此也没有的调用。C 语言是一种面向过程的语言,它主要通过函数来进行代码的组织和模块化。 如果你想要模拟的行为,可以使用结构体和函数指针来实现。你可以定义一个结构体,将函数指针作为其中的成员,然后通过调用函数指针来实现似于方法调用的效果。 以下是一个简单的示例: ```c #include <stdio.h> typedef struct { void (*print_message)(const char*); } MyClass; void print_hello(const char* message) { printf("Hello, %s!\n", message); } int main() { MyClass myObject; myObject.print_message = &print_hello; myObject.print_message("World"); return 0; } ``` 在上面的例子中,我们定义了一个名为 MyClass 的结构体,其中包含一个函数指针成员 print_message。然后我们定义了一个函数 print_hello,它接受一个字符串作为参数并打印出相应的消息。 在 main 函数中,我们创建了一个 MyClass 型的对象 myObject,并将 print_hello 函数的地址赋值给了 myObject 的 print_message 成员。然后我们通过调用 myObject.print_message("World") 来调用 print_hello 函数,并传递 "World" 作为参数。 这样就实现了似于的调用的效果。当然,这种方式只是一种模拟,不具备的封装、继承、多态等特性。如果需要使用更高级的面向对象特性,建议考虑使用支持面向对象编程的语言,如 C++

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值