我的問題訪問派生類的信息如下:有問題的設計modifiying /使用基本對象
int main()
{
Base* derivedobject = new Derived1();
derivedobject->GetProperties()-> ???
return 0;
}
//********************
// BaseClass.h
//********************
struct PropertyStruct
{
int x;
};
class Base
{
public:
Base();
~Base();
virtual PropertyStruct GetProperties() = 0;
private:
};
//********************
// DerivedClass1.h
//********************
struct PropertyStruct
{
int y;
};
class Derived1 : public Base
{
public:
Derived1();
~Derived1();
PropertyStruct GetProperties() { return myOwnDifferentProperties; };
private:
};
//********************
// DerivedClass2.h
//********************
struct PropertyStruct
{
float z;
};
class Derived2 : public Base
{
public:
Derived2();
~Derived2();
PropertyStruct GetProperties() { return myOwnDifferentProperties };
private:
};
如果我那樣做,我會得到一個錯誤,指出PropertyStruct是重新定義。如果我使用命名空間或重命名派生類中的結構,那麼我會得到一個錯誤,告訴我返回類型與Base定義的不同。 如果我將虛函數的返回類型定義爲它編譯的指針,雖然從主方法(在本例中)訪問函數「GetProperties」時的下一個問題是基類對象不知道變量結構中的變量是什麼類。
有沒有什麼辦法可以實現這一點? 我可以得到每個派生對象的不同屬性,但使用基類對象?
您可以使用不同名稱建立兩個「PropertyStruct」之間的基礎派生關係。 – iammilind 2012-07-26 15:39:44