이 질문은 이미 알고 있지만 아직 찾지 못했던 대답은 없습니다. 나는 기본 클래스에 대한 포인터 벡터를 만들고 모든 종류의 파생 클래스를 그 클래스에 추가하고있다. 이제 기본 클래스에는 파생 클래스 모두에서 재정의되고 각 클래스에 고유 한 가상 함수가 있습니다. 따라서 벡터를 통해 해당 객체를 검색하고 해당 객체에서 함수를 호출하면 올바른 객체를 호출해야합니다.하지만 기본 클래스 버전 만 호출하면됩니다. 나는 심지어 벡터에서 그들을 검색 할 때 개별 클래스를 원래 클래스로 캐스팅하려고 시도하지만 캐스팅을 거부합니다! 예 :벡터에서 벡터로 된 오브젝트 캐스팅
vector<base*> myBase;
DerivedClass *myDerived = static_cast<DerivedClass> myBase[i];
내가 읽은 모든 내용에 반드시 나와야 함에도 불구하고 작동하지 않습니다. 내 디버거는이 모든 것에도 불구하고 myDerived는 여전히 유형 기반이며 내 가상 함수 버전이 호출되고 있다고합니다.
아이디어가 있으십니까? 계정을 확인
class BankAccount {
public:
BankAccount(string namein, string typein){
name = namein;
type = typein;
balance = 0;
}
virtual string getType();
virtual void printTransactions() = 0;
virtual int withdraw(double amt){
return getBalance() -amt;
}
};
class SavingsAccount: public BankAccount {
public:
SavingsAccount(string namein, string typein);
void addTransaction(string transType, string name);
virtual int withdraw(double amt);
void printTransactions();
virtual string getType();
private:
};
SavingsAccount::SavingsAccount(string namein, string typein): BankAccount(namein, typein) {
}
int SavingsAccount::withdraw(double amt){
double aBal = getBalance() - amt;
if (aBal > 0){
setBalance(aBal);
}
return getBalance() - amt;
}
class CheckingAccount: public SavingsAccount {
public:
CheckingAccount(string nameIn, string typein): SavingsAccount(nameIn, typein){
}
virtual int withdraw(double amt);
void printTransactions();
string getType(){
return "Checking";
}
};
int CheckingAccount::withdraw(double amtIn){
double newBal = getBalance() - amtIn;
if (newBal < 500.00 && newBal > 2.49) {
setBalance(newBal - 2.50);
}
return newBal;
}
int main(int argc, const char * argv[])
{
vector<BankAccount*> myAccts;
SavingsAccount *mySav;
CD *myCD;
CheckingAccount *myCheck;
switch (option) {
case 1: {
string name;
string type;
cout << "Enter name: ";
cin >> name;
getline(cin, dump);
cout << "Enter account type: ";
cin >> type;
getline(cin, dump);
if (type.compare("Checking") == 0) {
CheckingAccount myCheck1 = CheckingAccount(name, type);
myAccts.push_back(&myCheck1);
}
case 3:{
for (int x = 0; x < myAccts.size(); x++) {
if (myAccts[x]->getName() == name && myAccts[x]->getType() == type) {
if (type == "Savings") {
mySav = static_cast<SavingsAccount*>(myAccts[x]);
double y = mySav->withdraw(amt);
if (y < 0){
cout << "Insufficient funds!";
}
}
if (type == "Checking") {
myCheck = myAccts[x]->GetDerived();
double y = myCheck->withdraw(amt);
if (y < 0){
cout << "Insufficient funds!";
}
if (y < 497.5) {
cout << "Withdrawal fee: $ 2.50" << endl;
}
}
}
은 저축 예금의 자식입니다. 죄송합니다.
DerivedClass * myDerived = static_cast myBase [i]; –
radar
'dynamic_cast'를 사용하십시오 - static_cast보다 우수합니다. –
동적 캐스트는 Null을 반환합니다. – user3712524