我的团队和我正在使用C ++(OOP范例)。我们必须实现DataType DtClassA
和两个派生类DtClassB
和DtClassC
。
我们这样做了:
// DtClassA.h
class DtClassA {
private:
int id;
public:
DtClassA();
int getId();
};
// DtClassA.cpp
DtClassA::DtClassA() {
this->id = 0;
}
int DtClassA::getId() {
return this->id;
}
// DtClassB.h
class DtClassB: public DtClassA {
private:
bool isAlive;
public:
DtClassB();
bool getIsAlive();
}
// DtClassB.cpp
DtClassB::DtClassB() : DtClassA() {
this->isAlive = true;
}
bool DtClassB::getIsAlive() {
return this->isAlive;
}
// DtClassC.h
class DtClassC: public DtClassA {
private:
char type;
public:
DtClassC();
char getType();
}
// DtClassC.cpp
DtClassC::DtClassC() : DtClassA() {
this->type = 'm';
}
char DtClassC::getType() {
return this->type;
}
// main.cpp
int main() {
DtClassB ctb = DtClassB();
createA(ctb);
}
createA(DtClassA& dta) {
cout << dta.getId() << endl; // We can do this.
cout << dta.getIsAlive(); // We cannot do this.
}
在main.cpp
文件中,我们必须实现函数createA(DtClassA& dta)
。
此函数可以接收DtClassB
或DtClassC
,但在这两种情况下,我们无法访问DtClassA
中未声明的方法。
有一些方法可以访问getIsAlive()
函数中的方法createA(DtClassA& dta)
吗?
答案 0 :(得分:0)
我们设法通过dynamic_cast解决了我们的问题(感谢pm100)。
这里是代码:
// DtClassA.h
class DtClassA {
private:
int id;
public:
DtClassA();
// To make a dynamic_cast, we needed to define "getId()" as virtual.
virtual int getId();
};
// DtClassA.cpp
DtClassA::DtClassA() {
this->id = 0;
}
int DtClassA::getId() {
return this->id;
}
// DtClassB.h
class DtClassB: public DtClassA {
private:
bool isAlive;
public:
DtClassB();
bool getIsAlive();
}
// DtClassB.cpp
DtClassB::DtClassB() : DtClassA() {
this->isAlive = true;
}
bool DtClassB::getIsAlive() {
return this->isAlive;
}
// DtClassC.h
class DtClassC: public DtClassA {
private:
char type;
public:
DtClassC();
char getType();
}
// DtClassC.cpp
DtClassC::DtClassC() : DtClassA() {
this->type = 'm';
}
char DtClassC::getType() {
return this->type;
}
// main.cpp
int main() {
DtClassB ctb = DtClassB();
createA(ctb);
}
createA(DtClassA& dta) {
cout << dta.getId() << endl; // We can do this.
try {
auto dtb = dynamic_cast<ClassB &>(dta);
} catch (std::bad_cast &e) {
cout << "Failed to cast DtClassA to DtClassB!" << endl;
}
try {
auto dtc = dynamic_cast<ClassC &>(dta);
} catch (std::bad_cast &e) {
cout << "Failed to cast DtClassA to DtClassC!" << endl;
}
// In "main()" function we call this function with an instance of
// DtClassB, so the first try-catch will pass and the second will
// not.
// So, now, we can do this:
cout << dta.getIsAlive(); // getIsAlive() is an operation from DtClassB.
}