向前声明和typeid的
-
20-09-2019 - |
题
我想检查针对一个子类A
的类型的超类B
的类型(与超类A
内部的方法,使B
将继承它)。
这就是我认为的伎俩(即,使用前声明):
#include <iostream>
#include <typeinfo>
using namespace std;
class B;
class A {
public:
int i_;
void Check () {
if (typeid (*this) == typeid (B))
cout << "True: Same type as B." << endl;
else
cout << "False: Not the same type as B." << endl;
}
};
class B : public A {
public:
double d_;
};
int main () {
A a;
B b;
a.Check (); // should be false
b.Check (); // should be true
return 0;
}
然而,该代码不能编译。我得到的错误是:
main.cc: In member function ‘void A::Check()’:
main.cc:12: error: invalid use of incomplete type ‘struct B’
main.cc:6: error: forward declaration of ‘struct B’
我怎么能解决这个问题?
解决方案
我认为你正在试图解决的问题是由虚拟方法更好的处理方式:
class A
{
public:
virtual bool Check() { return false; };
}
class B : public A
{
public:
// override A::Check()
virtual bool Check() { return true; };
}
在基类A 方法不应该需要知道对象是否是“真”的A或B.一个这是一个违反了基本的面向对象设计原则。如果该行为需要改变时的对象是B,则该行为应当在B中定义的和由虚拟方法调用处理。
其他提示
只需移动检查的()的定义出A的主体的:
#include <iostream>
#include <typeinfo>
using namespace std;
class B;
class A {
public:
int i_;
void Check ();
};
class B : public A {
public:
double d_;
};
void A::Check () {
if (typeid (*this) == typeid (B))
cout << "True: Same type as B." << endl;
else
cout << "False: Not the same type as B." << endl;
}
int main () {
A a;
B b;
a.Check (); // should be false
b.Check (); // should be true
return 0;
}
的一种方法是拉Check
的定义出来的类定义的,使得B
定义为当编译器获取对函数定义。
class A {
//...
void Check();
//...
};
class B { /* ... */ };
void A::Check() {
//...
}
将你的类B的声明下方的检查的定义。
只是B的声明之后移动功能体。
#include <iostream>
#include <typeinfo>
struct A
{
int i_;
void Check();
};
struct B : A
{
double d_;
};
void A::Check()
{
using namespace std;
if (typeid (*this) == typeid (B))
{
cout << "True: Same type as B." << endl;
}
else
{
cout << "False: Not the same type as B." << endl;
}
}
int main()
{
A a;
B b;
a.Check(); // should be false
b.Check(); // should be true
return 0;
}
您好, 即使你把A的定义::检查类之外的结果不会是你所期望的。这是因为,B对象此转换为目的的方法,以便它指向一个目的上从而typeids总是不同的。为了解决这个声明方法虚拟
不过,我还是不明白,你为什么要进行这样的测试O_O?正如CAdaker说,这是不好的做法
不隶属于 StackOverflow