c++ - 前向声明不适用于转换运算符

标签 c++ operators forward-declaration

考虑下一段代码:

#include <iostream>
using namespace std;


class B;

class A
{
public:

    A() { p = 1;}
    int p;
    operator B() {B b; b.x = this->p; return b;}
};


class B
{
public:
    int x;
};

int main()
{

    A a;
    B b = a;
    return 0;
}

我正在尝试将 A 转换为 B ,但我得到以下编译器提示:

..\main.cpp:13: error: return type 'struct B' is incomplete

当我这样做时:

#include <iostream>
using namespace std;

class B
{
public:
    int x;
};

class A
{
public:

    A() { p = 1;}
    int p;
    operator B() {B b; b.x = this->p; return b;}
};


int main()
{
    A a;
    B b = a;
    return 0;
}

代码可以编译,但问题是:使用我上面写的前向声明是否可以做到这一点?

非常感谢 罗嫩

最佳答案

可以,只要 A::operator B 的定义遵循 class B 的定义即可。

#include <iostream>
using namespace std;


class B;

class A
{
public:

    A() { p = 1;}
    int p;
    operator B();
};


class B
{
public:
    int x;
};

inline A::operator B() {B b; b.x = this->p; return b;}


int main()
{

    A a;
    B b = a;
    return 0;
}

关于c++ - 前向声明不适用于转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272622/

相关文章:

c++ - 传递给函数时数组为空

c++ - 梳状排序在 C++ 中不起作用

PHP 非假空合并运算符

objective-c - Class 类在哪里声明/如何转发声明它?

c++ - C++ union 中的命名结构

c++ - 使用私有(private)析构函数绕过模板错误

c++ - 大数字

javascript - 除加法 (+) 外,所有 JavaScript 算术运算符均有效

sql-server - SQL Server 中的按位运算

c++ - 方法的前向声明