c++中运算符[]只能用什么运算符来重载
2个回答
展开全部
重载[]操作符:
1. 双目操作符,第一操作数是重载此操作符的对象,第二操作数是无符号下标。
2. C++不允许把下标操作符函数作为外部函数来定义,它只能是非静态的成员函数。
3. 为了能对数组赋值,一般将返回值声明为引用类型。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Data1d{
vector<double> data1d;
int length1d;
public:
Data1d(int lg=0, double elem=0):length1d(lg){
for (int i=0; i<lg; i++)
data1d.push_back(elem);
//length1d=data1d.size();
}
void pushback(double elem){data1d.push_back(elem); ++length1d;}
void popback(){data1d.pop_back(); --length1d;}
int length(){return length1d;}
double& operator[](const int idx){
if (idx < 0 || idx >= length1d){
cerr << "ERROR: Index Out of Range, Last Element Returned!" << endl;
return data1d[length1d - 1];
}
return data1d[idx];
}
friend ostream& operator<<(ostream&, Data1d&);
};
ostream& operator<<(ostream& o, Data1d& mydata1d){
cout << "Data(" << mydata1d.length1d << "):\t";
for (int i=0; i<mydata1d.length1d; i++)
o << mydata1d[i] << ' ';
return o;
}
int main(){
Data1d mydata1d(5,0);
cout << mydata1d << endl;
for (int i=1; i<=5; i++)
mydata1d.pushback(i);
cout << mydata1d << endl;
for (int i=0; i<=mydata1d.length(); i++)
mydata1d[i]=i;
cout << mydata1d << endl;
mydata1d.popback();
cout << mydata1d << endl;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询