我在使用独立程序复制的其中一个项目中遇到错误。我确实看到了几篇与此相关的帖子,但无法弄清楚我的问题。此代码出现以下错误:“错误:预期的构造函数、析构函数或类型转换在‘&’标记之前”
#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()
返回的值会给您未定义的行为。
只需以这种方式更改函数的原型(prototype):
Y::X_ptr Y::func1()
// ^^^^^
// Returning the smart pointer by value now
{
X_ptr p(new X(8));
return p;
}
关于c++ - 错误 : expected constructor, 析构函数,或源文件中用户定义类的 '&' token 之前的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16789847/