这里很难解释我想要做什么,但我有一个基类和两个继承此基类的类。两个继承它的类都有自己独特的成员。我希望能够将两者都传递给方法,并让该方法检测它是哪一个,然后访问它们的唯一成员。我不能认为只会有两个继承它的类,所以我正在寻找更通用的解决方案。如何将类传递给方法,并从基类中检测继承者?
这里是想我做的一个例子:
#include <iostream>
class Base {
public:
int _type;
Base() { }
};
class First : public Base {
public:
int _first_only;
First() { }
};
class Second : public Base {
public:
int _second_only;
Second() { }
};
void test (Base b) {
std::cout << "Type: " << b._type << std::endl;
if(b._type==1) {
std::cout << "First\n";
// Want to be able to do this
std::cout << "Val: " << (First)b._first_only << std::endl;
} else if(b._type==2) {
std::cout << "Second\n";
// And this
std::cout << "Val: " << (Second)b._second_only << std::endl;
}
}
int main() {
First f;
f._first_only=1;
f._type=1;
Second s;
s._type=2;
s._second_only=2;
test(f);
test(s);
}