簡體   English   中英

將基類指針轉換為未知的派生類指針

[英]converting base class pointer to unknown derived class pointer

我有一個抽象基類的5個派生類。 每個派生類中都存在一個重載的函數 ,我們將其命名為print() 派生4類的示例:

Derived4::print(*Derived1)
Derived4::print(*Derived2)
Derived4::print(*Derived3)
Derived4::print(*Base)

就像我之前說過的,所有派生類都具有打印功能,但參數卻不同,例如

Derived1::print(*Derived2)
Derived1::print(*Derived3)
Derived1::print(*Derived4)
Derived1::print(*Base)

所有對象都存儲在像

vector<Base*> a

當我從vector中提取其中之一並嘗試調用print函數時,所有調用都定向到print(* Base)函數。我不允許存儲類型,因此不知道vector來自什么。 ,也不允許類型檢查。

一個例子:

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    void print(){cout << "greetings from A" << endl;}
};

class C : public A{
public:
    void print(){cout << "greetings from C" << endl;}
};

class D : public A{
public:
    void print(){cout << "greetings from D" << endl;}
}; 

class B : public A{
public:
    void print(C* c){c->print();}
    void print(A* d){d->print();}
};

int main()
{
    D d;
    C c;
    B b;
    vector<A*> a; //B,C,D will be stored inside a vector like this.
    a.push_back(&c);
    a.push_back(&d);
    b.print(a[0]);
    b.print(a[1]);
    return 0;
}

結果:

greetings from A
greetings from A

預期結果:

greetings from C
greetings from A

您需要虛擬功能。 A::print聲明為虛擬將使之成為事實,以便在類型為A的指針上調用print會調用構造對象的類的print ,而不是使用指針類型來決定要調用的print

您還需要刪除D::print ,如果對象為D類型,則會調用A::print

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    virtual void print(){ cout << "This is printed twice." << endl; }
};

class C : public A{
public:
    void print(){ cout << "This is desired output." << endl; }
};

class D : public A{

};

class B : public A{
public:
    void print(C* c){ c->print(); }
    void print(A* d){ d->print(); }
};

int main()
{
    D d;
    C c;
    B b;
    vector<A*> a; //B,C,D will be stored inside a vector like this.
    a.push_back(&c);
    a.push_back(&d);
    b.print(a[0]);
    b.print(a[1]);
    return 0;
}

結果:

This is desired output.
This is printed twice.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM