错误:在源文件中的用户定义类'&'令牌之前,预期的构造函数、析构函数或类型转换
error: expected constructor, destructor, or type conversion before '&' token for a user defined class in the source file
我在我的一个项目中遇到了一个错误,我使用独立程序复制了这个项目。我确实看到了一些与此相关的帖子,但无法找出我的问题。我在这段代码中得到以下错误:"错误:在'&'令牌之前期望构造函数、析构函数或类型转换"
#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;
}
相关文章:
- 构造函数和转换运算符之间的重载解析
- C++无效的函数类型转换
- 元组尺寸默认构造函数及其转换为std :: size_t
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 是否可以将一种函数类型转换为另一种采用相同参数但返回类型不同的函数类型
- 调用构造函数或转换
- 需要构造函数/析构函数/类型转换错误
- 使用构造函数自动转换
- static_cast转换构造函数与转换运算符
- 构造函数和转换
- C++ - 打印地图<结构,结构,构造函数>类型
- 错误:从"<未解析的重载函数类型>"转换为非标量类型
- 有没有一种干净的方法可以将 C# 'params object[]' 构造函数参数转换为C++构造函数?
- 混淆了复制构造函数和转换构造函数
- C++11:在按值传递参数初始化时转换构造函数和转换函数之间的歧义
- 继承构造函数+非默认构造函数类型的类内初始化失败
- 特征日志和exp函数类型转换错误
- c++ python构造函数类型错误(可能的命名空间问题)
- 构造函数的转换不适用于运算符重载
- 具有构造函数类型转换和转换操作符的转换序列