c++ - 如何在 C++ 中为前向声明类型实现一元运算符重载?

标签 c++ visual-studio-2008 operator-overloading forward-declaration unary-operator

以下代码无法在 Visual Studio 2008 中编译。当 Foo1 定义在 Bar 之前时,如何让它允许 Foo1 类中的一元运算符将其转换为 Bar?

class Foo1
{
public:
    int val;

    operator struct Bar() const;
};

struct Bar
{
    int val;
};

// This does not compile
Foo1::operator Bar() const
{
    Bar x;
    x.val = val;
    return x;
}

最佳答案

或者你可以:

//forward declaration of Bar
struct Bar;

class Foo1
{
public:
    int val;

    operator Bar() const;
};

struct Bar
{
    int val;
};

//Now it should compile
Foo1::operator Bar() const
{
    Bar x;
    x.val = val;
    return x;
}

关于c++ - 如何在 C++ 中为前向声明类型实现一元运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4675696/

相关文章:

c++ - 使用 std::equal_range 在某些范围内搜索 vector

python - 查询Linux操作系统上某个进程的所有实例的CPU总使用率

c++ - 位技巧和魔术

c# - 如何调试通过 Assembly.Load(byte[]) 加载的程序集?

c# - 如何在安装新版本期间强制部署项目更新文件?

c++ - 在 header 或 .cpp 中重载输入操作 >>

C++ 和 CTime & 系统时钟更改

c# - 为什么 C# 编译器使用隐式运算符返回的值的父类型来调用重载运算符

c++ - 如何使用模板函数减去两个对象?

c++ - shobjidl.h 中的第二个 C 链接