I have issues about forward declaration .
namespace downloader {
class IHttpThreadCallback ;
class MemoryHttpRequest ;
}
when I cast
auto responseHttpRequest = dynamic_cast<downloader::MemoryHttpRequest*>(m_callback);
It show warning incomplete type . How should I try , please suggest to me .
beside that I try to include class , but it not work and I think it not good idea . Thank you very much
It show warning incomplete type . How should I try , please suggest to me.
To use dynamic_cast
, the type must be complete. Solution: include the definition.
beside that I try to include class , but it not work and I think it not good idea .
Including the class definition is not only a good idea, but mandatory if you need to use dynamic_cast
. In this case, using a forward declaration is not a solution to your problem.
in my situation , the class which I need is defined in .cpp file
In that case, you cannot downcast into that type - unless you move the class definition into a header that you include.
dynamic_cast uses the vtable to interrogate and navigate the class hierarchy. it also needs to know the class content/layout in order to calculate offsets. that is why the compiler needs to know the class definition. static_cast needs to have a relationship between the classes.
if you are sure about the return value and are happy to avoid the runtime/type check then you might consider using a reinterpret_cast.
otherwise you will need to include the definition.
I put an example together
#include <iostream>
#include <vector>
#include <iostream>
namespace n {
class A;
class B;
n::A* f();
}
std::ostream& operator<<(std::ostream& os, n::A& a);
std::ostream& operator<<(std::ostream& os, n::B& b);
int main()
{
n::A* a(n::f());
n::B* b=reinterpret_cast<n::B*>(n::f());
std::cerr << "a: " << *a << std::endl;
std::cerr << "b: " << *b << std::endl;
}
namespace n {
class A
{};
class B: public A
{};
n::A* f() {
return new A();
}
}
std::ostream& operator<<(std::ostream& os, n::A& a) {
os << "in A";
return os;
}
std::ostream& operator<<(std::ostream& os, n::B& b) {
os << "in B";
return os;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.