2014-10-30 60 views
0

我具有如下面的實施2簡單的C++頭:C++無法訪問抽象類的向量元素?

Attribute.h

#include <string> 
using namespace std; 

class IAttribute 
{ 
    virtual string getName(){}; 
}; 

class StringAttribute : public IAttribute 
{ 
private: 
    string name = ""; 
    string value = ""; 

public: 
    StringAttribute(string name, string value) 
    { 
     this->name = name; 
     this->value = value; 
    } 
    string getName() 
    { 
     return this->name; 
    } 
    string getStrValue() 
    { 
     return value; 
    } 
    void setValue(string value) 
    { 
     this->value = value; 
    } 
}; 

tableRow.h

#include "attribute.h" 
#include <vector> 
using namespace std; 
class TableRow 
{ 
private: 
    vector<IAttribute *> attributeList; 
    int rowId; 

public: 
    TableRow(int rowId) 
    { 
     this->rowId = rowId; 
    } 

    void addStrAttribute(string name, string value) 
    {  
     attributeList.push_back(new StringAttribute(name, value)); 
    } 
    StringAttribute getStrAtt(string name) 
    { 
     for (int i = 0; i < (int)attributeList.size(); i++) 
     { 
      if (attributeList[i]->)//couldn't access the methods of StringAttributeImp 
      { 

      } 
     } 
    } 
}; 

如的TableRow報頭的上面的評論,我不能」訪問實現類的方法和屬性。哪裏不對?

+1

即使您將getName()公開,代碼也不會被編譯。例如,getName()不是抽象的,它具有不返回字符串的實現。 IAttribute不具有虛擬析構函數。注意代碼中的這些問題。 – Jagannath 2014-10-30 22:37:37

回答

2

getName功能是privateIAttribute類。所以當然你無法訪問它。

+0

現在我可以訪問getName方法,但無論如何要訪問StringAttribute中的方法而不將其列入IAttribute抽象類中? – AWT 2014-10-30 22:39:58

+0

您可以使用'dynamic_cast'來檢查從'vector'檢索到的'IAttribute *'指針是否指向一個'StringAttribute'對象。如果是這樣,你將擁有需要訪問其成員的'StringAttribute *'指針。 – 2014-10-30 23:03:36

+0

@AbdulwadoudTah:不,你認爲有什麼'IAttribute'的意思?這是列出常見的成員。所以現在就開始做吧。 – 2014-10-31 00:44:40

1

您應該將getName函數更改爲public;或使用朋友班。