C++——const成员

这里先用队列举例:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <assert.h>
using namespace std;
class SeqList
{
public:
	void pushBack(int data)
	{
		if (_size == _capacity)
		{
			int* tmp = (int*)realloc(a, sizeof(int) * 4);
			if (tmp == NULL)
			{
				perror("realloc fail::");
				return;
			}
			a = tmp;
			_capacity += 4;
		}
		a[_size++] = data;
	}
	int operator[](size_t i) const
	{
		assert(i < _size);
		return a[i];
	}
	void Print() const
	{
		for (int i = 0; i < _size; i++)
		{
			cout << a[i] << " ";
		}
		cout << endl;
	}
private:
	int* a = (int*)malloc(sizeof(int) * 4);
	size_t _size = 0;
	size_t _capacity = 0;
};
int main()
{
	SeqList sl;
	sl.pushBack(1);
	sl.pushBack(2);
	sl.pushBack(3);
	sl.pushBack(4);
    cout << sl[3];
	return 0;
}

进行[ ]重载,可以通过 sl[i]来访问数据。但是,我们的重载函数是传值返回,返回的是原来的数的拷贝,是一个临时变量,具有常量性,也就是不可以进行修改。

如下,进行修改是会报错的:

所以,我们考虑使用引用返回,一般,我们采用引用返回的都是全局变量,static静态变量,*this。这里返回的a[i]变量是在堆上的,所以出了函数还可以存在,所以可以使用引用返回。


同时,以上两个函数构成重载(参数类型不同)

【注意】:只是返回值不同不能构成重载。

第二个函数是针对普通数据,可读可写

第一个函数是针对特殊数据,只能读不能写。

=================================================================

【BTW】:

非const变量可以调用const函数(权限的缩小)

const变量不可以调用非const函数(权限的放大)

=========================================================================

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

cpp 复制代码
Class Date
{
    public:
        Date* operator&()
            { 
                return nullptr;
            }
        const Date* operator&() const
            { 
                return nullptr;
            }
    private:
        int _year;
        int _month;
        int _day;
}

这两个运算符一般不需要重载,使用编辑器生成的默认取地址重载即可。只有特殊情况下才会重载,比如说,不想让别人取到有效地址。

相关推荐
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼5 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛