visual C++无法访问抽象类的向量的元素

visual C++ cannot access element of vector of abstract class?

本文关键字:向量 元素 抽象类 访问 C++ visual      更新时间:2023-10-16

我有两个简单的C++头,实现如下:

属性.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头的注释所示,我无法访问Implementation类的方法和属性。怎么了?

getName函数是IAttribute类中的private。所以你当然不能访问它。

您应该将getName函数更改为public;或者使用好友类。