如何访问派生类中的聚合

How to access aggregate in a derived class

本文关键字:派生 何访问 访问      更新时间:2023-10-16

我知道有些人会说这是对象切片问题,但我不认为是。我在这个网站上看到了很多相关的帖子,但并不完全相同。让我们从代码开始:

#include "stdafx.h"
#include <list>
struct MY_STRUCT
{
    int a;
    int b;
};
class File
{
public:
    virtual void Load(char * fileName) = 0;
};
class ExcelFile : public File
{
protected:
    std::list<MY_STRUCT> my_list;
public:
    ExcelFile(){};
    ~ExcelFile(){};
    virtual void Load(char * fileName)
    {
        // load the file into my_list
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    char fileName[] = "test.txt";
    File * file = new ExcelFile;
    file->Load( fileName );
    // Now I need to fill a Windows List or CListView from my_list data but how?
    // I can't access or iterate my_list here and I am not too sure if
    // should pass a windows object to the class to fill it up?
    // Even if I iterate by adding a member function to return the list object, wouldn't not
    // it violate the data encapsulation rule thereby defeating the purpose of having
    // interface class?
    return 0;
}

所以基本上我有一个接口类,其派生类在聚合(集合)中具有数据。现在我想显示数据。正确的方法是什么?我已经在代码的注释中提到了这个问题......我想我在写这篇文章时已经找到了答案,我应该让类添加填充列表的功能。我想如果我必须填写列表框或列表视图,那么我需要为每个列表使用两个函数。我想知道我是否可以在访客模式方面做得更好!?

似乎(如果我正确理解您的问题)不必担心对象拼接。看起来您要做的只是查看"聚合"类中的列表,在本例中: ExcelFile()

添加一个方法ExcelFile(),也许是像print()这样的东西,或者如果你想变得花哨:

std::ostream & operator<<(std::ostream &os) {
    std::list<MY_STRUCT>::iterator it;
    for (it = my_list.begin(); it != my_list.end(); ++it) {
        os << "A: " << it.a << ", B: " << it.b << std::endl;
    }
    return os;
}

注意:代码尚未编译或运行,它只是一个准则。

编辑

如果 OP 想在其他地方使用他的列表,则返回对该集合的常量引用:

const std::list<MY_STRUCT> & getSet() const {
   return my_list;
}

只需为您的my_list成员提供一个 getter,以便从类外部安全访问(这不会违反任何封装规则!

class ExcelFile
{
public:
    // ...
    const std::list<MY_STRUCT>& getMyList() const { return my_list; }
    // ...
}