错误:在源文件中的用户定义类'&'令牌之前,预期的构造函数、析构函数或类型转换

error: expected constructor, destructor, or type conversion before '&' token for a user defined class in the source file

本文关键字:构造函数 类型转换 析构函数 定义 用户 源文件 令牌 错误      更新时间:2023-10-16

我在我的一个项目中遇到了一个错误,我使用独立程序复制了这个项目。我确实看到了一些与此相关的帖子,但无法找出我的问题。我在这段代码中得到以下错误:"错误:在'&'令牌之前期望构造函数、析构函数或类型转换"

#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
class X
{
private:
    int _x;
public:
    X(int x) : _x(x) {};
};
class Y
{
private:
    typedef boost::shared_ptr<X> X_ptr;
public:
    X_ptr& func1();
};
X_ptr& Y::func1()
{
   X_ptr p(new X(8));
   return p;
};
int main()
{
   return 0;
}
有人能帮我解决这个错误吗?

有两个问题。首先,您忘记限定类型名称X_ptr:

    Y::X_ptr& Y::func1()
//  ^^^     ^
//          BUT REMOVE THIS!
第二,注意您返回了一个引用到一个局部变量。试图解引用func1()返回的值将会给您未定义的行为。

只需这样修改函数的原型:

Y::X_ptr Y::func1()
// ^^^^^
// Returning the smart pointer by value now
{
    X_ptr p(new X(8));
    return p;
}