【发布时间】:2017-06-18 03:17:30
【问题描述】:
我正在构建一个秘密消息类,其中包含消息中的行向量以及每条消息可以查看的最大次数。我正在尝试重载 [] 运算符以便能够看到消息。
例如:如果我想初始化下面的字符串向量,我应该可以这样做......
vector<string> m = {
"Here is the first line",
"I have a second line as well",
"Third line of message"};
//initialize message - each line may be viewed a maximum of two times
SelfDestructingMessage sdm(m, 2);
cout << sdm[0] << endl;
//outputs "Here is the first line" and decrements remaining views of first line by one
我的问题是,我在头文件中声明了操作符,然后在函数文件中定义如下:
string SelfDestructingMessage::operator[](size_t index){
return const string & message[index];
}
因此,我应该能够使用带有 size_t 参数(索引)的 [] 运算符查看实际消息。它应该返回对从特定于对象的消息向量索引的消息字符串的 const 引用。
但是在编译时,我得到一个“错误:在'const' return const string & message[index];之前的预期主表达式;”
你知道这是什么原因吗?
【问题讨论】: