65,210
社区成员
发帖
与我相关
我的任务
分享
struct RedGroup
{
vector<string> vRecords;
string operator [] (unsigned int index)
{
return vRecords[index];
}
};
string strLine = redGroup[0];
//报错:error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const RedGroup' (or there is no acceptable conversion)
const RedGroup A;
string s = A[0]; // error C2678: 二进制“[”: 没有找到接受“const RedGroup”类型的左操作数的运算符(或没有可接受的转换)
string operator [] (unsigned int index)const //后面加个const就可以了
{
return vRecords[index];
}
RedGroup rgFind;
rgFind.push_back(redGroup[0]); //调用[],没有报错
//这里的RedGroup
//添加了部分函数:
struct RedGroup
{
vector<string> vRecords;
unsigned int size() const
{
return vRecords.size();
}
string operator [] (unsigned int index)
{
return vRecords[index];
}
void push_back(const string& str)
{
vRecords.push_back(str);
}
void clear()
{
vRecords.clear();
}
bool operator < (const RedGroup& r)
{
return vRecords[0] < r.vRecords[0];
}
bool operator > (const RedGroup& r)
{
return vRecords[0] > r.vRecords[0];
}
bool operator == (const RedGroup& r)
{
return vRecords[0] == r.vRecords[0];
}
};#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct RedGroup
{
RedGroup(string s)
{
vRecords.push_back(s);
}
vector<string> vRecords;
string operator [] (unsigned int index)
{
return vRecords[index];
}
};
int main()
{
RedGroup redGroup("OK");
string strLine = redGroup[0];
cout << strLine << endl;
return 0;
}