[英]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;
}
因此,基本上我有一個接口類,其派生類具有聚合(集合)中的數據。 現在我要顯示數據。 什么是正確的方法? 我在代碼的注釋中提到了問題...我想我在寫這篇文章時找到了答案,我應該讓類添加函數來填充列表。 而且我想我是否必須填充ListBox或ListView而不是需要為每個列表使用兩個函數。 我想知道我能否用訪客模式做得更好!?
不會出現(如果我正確理解了您的問題)不必擔心對象拼接。 看來您要做的就是從“ aggregate”類中查看列表,在這種情況下: 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; }
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.