考虑下一段代码:
#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/