2. 考虑将物体作为论据和印刷其类型的问题:
#include <iostream>
class A { };
class B : public A { };
class C : public A { };
class D : public C, public B { };
using namespace std;
template<class T>
void print_type(T* info)
{
if(dynamic_cast<D*>(info))
cout << "D" << endl;
else if(dynamic_cast<C*> (info))
cout << "C" << endl;
else if(dynamic_cast<B*>(info))
cout << "B" << endl;
else if(dynamic_cast<A*> (info))
cout << "A" << endl;
}
int main(int argc, char** argv)
{
D d;
print_type(&d);
return 0;
}
It gives me the following error: "Ambiguous conversion from derived class D to base class."
But I fail to see where s the ambiguity: if the object declared in main (d) is of type D, why can t be it directly converted to a type A?
Also, if I pass an argument of type string of course I get other errors:
std::basic_string<char> is not polymorphic
在 Java,有异构体:<Text A>
;在这种情况下是有用的。 我如何在C++中用模板做类似的事情?
我这样修改了法典:
#include <iostream>
#include <vector>
class A { };
class B : virtual public A { };
class C : virtual public A { };
class D : public C, public B { };
using namespace std;
template<class T>
void print_type(T* info)
{
if(dynamic_cast<D*>(info))
cout << "D" << endl;
else if(dynamic_cast<C*> (info))
cout << "C" << endl;
else if(dynamic_cast<B*>(info))
cout << "B" << endl;
else if(dynamic_cast<A*> (info))
cout << "A" << endl;
}
int main(int argc, char** argv)
{
string str;
print_type(&str);
return 0;
}
但我仍然有错误:<>>>>。 st st bas ; ; ;