0
#include <iostream>
#include <string>
string &parse(string str,int from){
   string *data=new string[6];
    ....
    ....
   return *data;
}


int main(){
string data[6];
data=parse(str,18); //ERR: std::string must be a modifiable lvalue
}

我得到了上面的错误,我正在考虑创建 operator=,对吗?如果是这样,我试过这个

string operator=(const string& other){} //ERR: operator= must be a member function

但我得到另一个错误。谢谢你的帮助。

4

3 回答 3

4

您的代码确实需要重构,不要使用字符串数组 - 使用字符串向量:

std::vector<std::string> parse(string str,int from){
   std::vector<std::string> data(6);
    ....
    ....
   return data;
}

int main(){
    std::vector<std::string> data=parse(str,18);
}
于 2013-09-01T20:44:09.470 回答
2

parse()返回对 a 的引用std::string,因此当您取消引用本地字符串数组时,您将返回对数组第一个字符串的引用。
main()您将该引用分配给一个字符串数组时,这根本没有意义。
实现您想要做的事情的最佳选择是使用std::vector

std::vector<std::string> parse()
{
    std::vector<std::string> v(6);

    ...

    return v;
}

int main()
{
    std::vector<std::string> data;

    data = parse();
}

向量按值返回,但不存在性能问题,因为向量可以轻松移动而不是复制。

如果您不能使用std::vector(例如,因为您正在尝试学习和理解动态数组),您可以返回一个指向您在开始时分配的动态数组的指针parse()

std::string* parse()
{
    std::string* strs = new std::string[6];

    ...

    return strs;
}

int main()
{
    std::string* data;

    data = parse();

    ...

    delete[] data; //Don't forget to release the array memory!
}
于 2013-09-01T20:48:15.990 回答
1

if you really want to do it without vectors ( you should use vectors, but anyway.. ) you have to get your types right:

string*: pointer to string (can be several strings next to each other), string&: reference to single string.

#include <string>
using namespace std;

// return type is "pointer to string", not "reference to string"
string* parse(string str,int from){
   string *data=new string[6];
   return data; // do not apply the *-operator here.
}

int main(){
string* data; // don't mention the size here. ( probably the error you got. )
data=parse("hmm..",18); // assign the result ( pointer ) to data
delete[] data; // don't leak memory
}

however i suggest you read up on pointers, references and what happens when you apply the *-operator. string * does not just mean "array of strings"

于 2013-09-01T20:59:06.690 回答