【问题标题】:How do I implement a unary operator overload for a forward declared type in C++?如何在 C++ 中为前向声明的类型实现一元运算符重载?
【发布时间】:2011-01-13 00:46:52
【问题描述】:

以下代码无法在 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;
}

【问题讨论】:

  • 你不需要struct Bar,C++的结构已经是类型了。
  • 我使用 struct Bar 作为前向声明,因为 Bar 的定义直到稍后才会出现。

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


【解决方案1】:

或者你可以:

//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;
}

【讨论】:

    【解决方案2】:

    我想出了答案。有两种解决方案:

    struct Bar;
    
    class Foo1
    {
    public:
        int val;
    
        operator struct Bar() const;
    };
    

    或者:

    class Foo1
    {
        typedef struct Bar MyBar;
    public:
        int val;
    
        operator MyBar() const;
    };
    

    (operator::Bar() 实现保持不变)

    【讨论】:

    • 它看起来不像是 C++ 的解决方案,而是编译器错误的解决方法。
    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多