如何访问派生类中的聚合
How to access aggregate in a derived class
我知道有些人会说这是对象切片问题,但我不认为是。我在这个网站上看到了很多相关的帖子,但并不完全相同。让我们从代码开始:
#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; }
// ...
}
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 如何从派生类访问基类中的重载运算符?
- 从派生类访问模板基类的构造函数
- 如何从派生类访问引用成员变量?
- C 成员从模板类型的派生类访问
- 从<T>派生类访问 Base 标识符是否必须>?
- 允许从特定派生类访问基类成员
- 如何通过派生类访问基类的受保护成员?
- 从公共派生类访问受保护的成员
- C++派生类访问基类成员
- 我可以从 C++ 中的派生实例访问指向基本实例的指针吗?
- C++是否可以从同级第二个派生对象访问第一个派生对象的受保护基础数据成员?
- 通过父类型的指针或直接从派生类访问成员函数的差异
- 多重继承C++-BaseA从派生类访问BaseB变量
- 从派生类访问基类公共成员
- 有没有办法使用派生类访问基类中的值
- 允许按派生类访问,但不允许重写
- 如何从派生类访问派生基成员?(C++年)
- 关于受保护的成员函数和派生类访问的混淆
- 从派生类访问基类对象