C++学习记录


前言

学习C++中const的学习记录

一、const

作用跟C类似,有区别的是在类声明的const成员变量可以不用声明的时候进行初始化,如果没有进行初始化就必须在构造函数的初始化列表中进行。

二、C++中的const成员函数

1.const优先调用非const函数,如果没有非const函数,那么就调用const函数

const优先调用非const函数:

#include <iostream>

using namespace std;

class Test
{
public:
	void print()
	{
    	cout << "Hi" << endl;
	}

	void print()const
	{
		cout << "嗨" << endl;
	}

};

int main()
{
    Test t;
	
	t.print();

	return 0;
}

如果没有非const函数,那么就调用const函数:

#include <iostream>

using namespace std;

class Test
{
public:

	void print()const
	{
		cout << "嗨" << endl;
	}

};

int main()
{
    Test t;
	
	t.print();

	return 0;
}

2.const 成员函数中只能调用const 成员函数

#include <iostream>

using namespace std;

class Test
{
public:

	void print()
	{
		cout << "嗨" << endl;
	}

};

int main()
{
    const Test t;
	
	t.print();

	return 0;
}

解决方法1:用const修饰的成员函数

#include <iostream>

using namespace std;

class Test
{
public:

	void print()const
	{
		cout << "嗨" << endl;
	}

};

int main()
{
    const Test t;
	
	t.print();

	return 0;
}

解决方法2:强制类型转换 :const_cast

#include <iostream>

using namespace std;

class Test
{
public:

	void print()const
	{
		cout << "嗨" << endl;
	}

};

int main()
{
    const Test t;
	
	const_cast<Test&>(t).print();

	return 0;
}

总结

1.const优先调用非const函数,如果没有非const函数,那么就调用const函数

2.const成员函数中只能调用const成员函数

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值