C2143错误c ++

cur*_*ity -2 c++ string

抱歉这个问题,但我被困住了.我有下面的语法:

class xx
{
..some simple fields like: int t;  // )))
public: class  anotherClass;
xx();
MyObj* obj();
string*  name(); //error C2143: syntax error : missing ';' before '*'   

}
Run Code Online (Sandbox Code Playgroud)

我写了# include <string> 编译器想要什么?!

seh*_*ehe 6

它希望你告诉他哪个字符串.你想要标准的:

class xx
{
  public:
    std::string*  name();
};
Run Code Online (Sandbox Code Playgroud)

现在,我不确定为什么要返回指向字符串的指针.如果你问我,这是一个等待发生的分段错误.两个对我来说似乎合理的可行选择:

class xx
{
    std::string _name;
  public:
    const std::string& name() const 
    { 
        return _name; // WARNING: only valid as long as 
                      // this instance of xx is valid
    }
};
Run Code Online (Sandbox Code Playgroud)

要么

class xx
{
  public:
    std::string name() const { return "hello world"; }
};
Run Code Online (Sandbox Code Playgroud)