【发布时间】:2012-05-26 23:11:10
【问题描述】:
我正在尝试通过使用类似于组合模式的东西来构建一个进度条类,该类可以包含任意数量的子进度条。
假设我有这门课pbar:
class pbar
{
public:
pbar(const int w) { width = w; } // already sets the
~pbar() {}
void setwidth(const int w) { width = w; } // set the width to w
void show() const;
void sync();
void add(const pbar bar)
{
// add's a subbar
subbars.pushback(bar);
}
private:
std::vector<pbar> subbars; // the sub-process progressbars
int width; // onscreen width of the pbar
};
如您所见,pbar 有两个成员:宽度和子进度条(它们本身就是pbars)。我一直在尝试实现一个sync 函数,该函数将subbars 中pbars 的所有宽度更改为与调用它的pbar 的宽度相匹配:
void pbar::sync()
{
for ( pbar bar : subbars )
{
bar.setwidth(width); // first set the width of the subbar
bar.sync(); // secondly make it sync up it's subbars
}
}
但这似乎不起作用。我试过使用这个测试程序:
int main()
{
pbar a(1);
pbar b(2);
pbar c(3);
pbar d(4);
c.add(d);
b.add(c);
a.add(b);
a.show();
std::cout << "syncing" << std::endl;
a.sync();
a.show();
}
show 函数定义为:
void pbar::show() const
{
std::cout << w << std::endl;
for ( pbar bar : subbars )
{
bar.show();
}
}
预期的输出是:
1
1
1
1
其实是这样的:
1
2
3
4
奇怪的是 show() 函数确实正确地迭代到所有子栏,但看起来 sync() 没有(事实上,使用 cout 我已经确认实际上 确实,但似乎没有效果)。
我的代码有什么问题?这不是使用 c++0x 类型的 for 循环,因为我尝试过使用较旧的迭代器循环。我找不到我犯的错误。我认为这与我在sync 中使用setwidth 时更改了错误的pbars 有关。
免责声明:这实际上是一个更大项目的一部分,并且该类比此处显示的要复杂得多,但我已经设法使用上面的代码重现了不需要的行为(顺便说一句,这不是复制粘贴,可能包含错字)
【问题讨论】:
标签: c++ algorithm composition