C++ 对每个递归结构执行一些操作';s元素,而不在C++;
任务:在C++ 对每个递归结构执行一些操作';s元素,而不在C++;,c++,recursion,recurrence,C++,Recursion,Recurrence,任务:在Presenter::present(…)方法(使用Presenter的私有成员)中对递归结构的每个元素执行操作,而不修改它(结构只有成员,除了构造函数之外没有方法) 问题:该结构除了构造函数之外没有任何方法 示例: 我有一个结构: struct Component{ std::vector<Component *> children; Component * parent; std::string ID; std::string conten
Presenter::present(…)
方法(使用Presenter
的私有成员)中对递归结构的每个元素执行操作,而不修改它(结构只有成员,除了构造函数之外没有方法)
问题:该结构除了构造函数之外没有任何方法
示例:
我有一个结构:
struct Component{
std::vector<Component *> children;
Component * parent;
std::string ID;
std::string content;
Component(ID, content){...}
};
我现在想要,将指针传递到我的演示者::present(…)
:
输出到std::string
(或控制台,nvm)所有ID
-内容对,如:
A a content sth
B b content sth
C1 c1 content sth
C2 c2 content sth
通过将一些recursivePresent(std::string&output)
方法添加到组件
结构中,可以很容易地实现这一点
但是我想知道是否可以在不修改组件
结构的情况下(不向其添加任何方法)执行此操作
EDIT(由于评论而产生):请注意,输出使用了一些演示者的私有/受保护的成员/方法-我不能假设它只是示例中的一个“某物”
我找不到这样的解决办法,但我相信这里有人会用一些疯狂的想法给我一个惊喜;) > P>运行时,C++ +代码>结构> <代码>(或代码>类<代码>)对象不知道它的结构、字段、布局或大小。这些只有在编译时才知道
如果添加一个新字段long newfield代码>在结构组件的末尾,代码中的大多数例程将保持不变(除了那些分配这种结构的例程,它们使用的是它的大小)
您需要一些运行时元数据来描述对象的结构。回答注释:@firda您能解释一下吗?我不知道你是什么意思。
我的评论是:为什么不在Presenter上使用它(recursivePresent助手?
class Presenter {
void presentRecursive(Component *c, std::ostream& out) {
out << c->ID << ' ' << c->content << std::endl;
for(auto p : c->children) presentRecursive(p, out);
}
public:
void present(Component *c) {
presentRecursive(c, std::cout);
}
};
课堂演示者{
无效预承包商(组件*c,标准::ostream&out){
out ID提示:成员recursivePresent(std::string&output)
本质上与非成员recursivePresent(const-Component&c,std::string&output)相同
假设所需的所有数据成员都是可访问的。然后执行此操作,只需创建一个递归present,它不在组件内部,但需要一个OK,但必须在Presenter::present(…)内部调用它
并可以访问其他演示者的成员/方法。我已对原始问题进行了编辑,很抱歉从一开始就不准确。为什么不使用它(recursivePresent帮助器)在Presenter上?您可以使用递归lambda来实现。现在,当我看到它时,它看起来非常清晰/明显。非常感谢:)这正是我想要实现的。不知何故,我想不起来(我现在觉得很傻)。再次感谢:)
A a content sth
B b content sth
C1 c1 content sth
C2 c2 content sth
class Presenter {
void presentRecursive(Component *c, std::ostream& out) {
out << c->ID << ' ' << c->content << std::endl;
for(auto p : c->children) presentRecursive(p, out);
}
public:
void present(Component *c) {
presentRecursive(c, std::cout);
}
};