⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo_operator_06.cpp

📁 对于一个初涉VC++的人来书
💻 CPP
字号:

//************************************************
// 定义向量类,重载二元下标运算符"[]"
// 注意:只能重载为类成员函数,而不能重载为友元函数
//************************************************

# include <iostream.h>
# include <stdlib.h>

const int MaxSize=10; //定义符号常量表示向量的最大长度

class Vector
{
public:
	Vector();
	int & operator [] (int index);
protected:
	int table[MaxSize];
};

Vector::Vector()
{
	for(int i=0;i<MaxSize;i++) table[i]=i;
}

int & Vector::operator [] (int index)
{
	if((index<0)||(index>MaxSize-1))
	{
		cout<<"Index out of bounds.\n";
		exit(1);
	}
	return table[index];
}

int main()
{
	Vector v;

	cout<<v[2]<<endl;
	v[2]=8;
	cout<<v[2]<<endl;
	cout<<v[10]<<endl;

	return 0;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -