gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:42 26 4
gpt4 key购买 nike

考虑下一段代码:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com