gpt4 book ai didi

C++ 转换为不完整类型

转载 作者:行者123 更新时间:2023-11-30 04:24:43 24 4
gpt4 key购买 nike

我想使用一个指针 ( _ref ) 指向不同的类类型。为了使用它,我必须将它转换为指定的类型。我不能这样做,因为第 5 行的类型不完整。如果我将 B 的定义移到第 5 行,它需要定义类 A。

#include <iostream>
#include <vector>
#include <string>

class B;

class A{
void *_ref;
std::string _reft;
public:
void setref(A &a){
_ref=&a;
_reft=typeid(a).name();
}
void setref(B &b){
_ref=&b;
_reft=typeid(b).name();
}
void test(){
if(_ref && _reft==std::string(typeid(B).name())){
std::cout<<"Ref to B: ";
static_cast<B*>(_ref)->test(); //error here
}
}
};

class B{
std::vector<A> a;
public:
A A(int i){
return a[i];
}
void test(){
std::cout<<"IT WORKS!";
}
};

int main(){
A a;
B b;
a.setref(b);
a.test();
return 0;
}

最佳答案

将需要B完成的函数的实现移出类;将它放在源文件中,或者在 B 的定义之后 inline:

class A{
// ...
void test();
};

class B{
// ...
};

inline void A::test(){
// ...
}

关于C++ 转换为不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535578/

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