首页 > 其他 > 详细

下标操作符

时间:2014-02-27 03:39:50      阅读:517      评论:0      收藏:0      [点我收藏+]

有一个vector存储的容器,用下标操作返回容器内的元素,类设计如下:

class Index
{
public:
	friend ostream& operator<<(ostream& os, const Index& org);

	Index(void);
	~Index(void);

	int& operator[] (const size_t);
	const int& operator[](const size_t) const; 

	int AddData(const int data);
	int RemoveData(const int data);
	vector<int> GetList() const;
	int SetList(const vector<int> &);

private:
	vector<int> vList;
};
ostream& operator<<(ostream& os, const Index& org);
下标操作应定义为类成员,因为跟类本身关系紧密,如下实现

int& Index::operator[](const size_t index)
{
	return vList[index];
}

const int& Index::operator[](const size_t index) const
{
	return vList[index];
}

由于要作为左值,所以返回为引用,而且可能有const不同类型的调用,所以有两个版本,测试用例如下

int nData;
	Index *index = new Index;
	while (cin>>nData)
	{
		index->AddData(nData);
	}
	if (!(index->GetList().empty()))
	{
		//printf("index[1] = %d\n", index->operator[](1)); // ok
		//printf("index[1] = %d\n", (*index)[1]); //ok
		//printf("index[1] = %d\n", index(1)); //error
		//cout << "index:" << (*index)[1] << endl; // error undefined "<<"

		cout << "index:" << *index << endl;
		
		//(*index)[1] = 1234;
	}
	
	if (index)
	{
		delete index;
		index = NULL;
	}
这里有个成员AddData主要用来加入元素,具体实现如下

int Index::AddData(const int data)
{
	vList.push_back(data);
	return 0;
}

在上面测试的时候,由于初开始没有定义<<操作符,所以只能使用printf先看输出结果;这里第一和第二都是正确的,但是第三情况一定要注意,初开始我就纳闷怎么老是输出一个奇怪的数字,其实是由于index是指针,而非直接的对象,所以是不对的;当然也能作为左值,最后一个赋值为1234的。

这里我还定义了<<操作符,所以默认也能输出,但是输出的东西就不是我能决定的了,因为测试或者使用的时候我就是用户,类是由设计者制定,如下:

ostream& operator<<(ostream& os, const Index& org)
{
	//vector<int>::iterator iter = org.GetList().begin()
	//for( ; iter!=org.GetList().end(); iter++)
	for (int i = 0; i != org.GetList().size(); i++)
	{
		os << org[i] << " ";
	}
	return os;
}
这里输出了所有成员,并不能要求具体的成员函数。



下标操作符,布布扣,bubuko.com

下标操作符

原文:http://blog.csdn.net/comwise/article/details/19935435

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!