使用成员函数打印对象
Using Member Functions to Print Object
我有一个类,它包含一个由vector< vector< Node > >
实现的树结构,其中Node
包含一堆通过getters/setters公开的属性。
class Tree
{
vector< vector< Node > > mGrid;
printTree(std::ostream& output = std::cout);
};
class Node
{
double property1 { return mProp1; }
double property2 { return mProp2; }
};
printTree()
当前硬连线为使用属性 tstep:
void Tree::printTree( ostream& output )
{
...
for (unsigned t = 0; t < mGrid.size(); ++t)
{
toPrint = "";
for (unsigned state = 0; state < mGrid[t].size(); ++state)
{
toPrint += to_string_with_precision( mGrid[t][state].tstep(), 1 );
...
是否有一些光滑/方便/面向对象的方式来概括这个函数,以便它可以打印出 Node 的任何属性(而不是只吐出硬连线的 tstep(( 属性或通过 if/then 语句本质上做同样的事情(。
我已经使用函数指针在 C 中做了这样的事情,但这C++,C++常见问题解答说不要弄乱指向成员函数的指针。
你可能想要模板函数:
class Tree
{
vector< vector< Node > > mGrid;
public:
template <typename F>
void ForEachNode(F&& f) {
int i = 0;
for (auto& v : mGrid) {
int j = 0;
for (auto& node : v) {
f(node, i, j);
++j;
}
++i;
}
}
};
那你可以做
void printTreeProp1(Tree& tree) {
tree.ForEachNode([](const Node& node, int i, int j) {
if (i != 0 && j == 0) {
std::cout << std::endl;
}
std::cout << node.property1() << " ";
});
}
第一次操作,所有循环都忽略了第一个元素。vector
从零开始,您使用的是++t
和++state
,这会增加循环顶部的值。这意味着您永远不会访问第 0 个元素(mGrid[0]
和mGrid[t][0]
(.
2nd,您没有包含tstep()
的定义,所以我们不知道您得到了什么。假设你想打印二维数组的每个维度,我认为你必须打破它。像这样:
class Node
{
protected:
double mProp1;
double mProp2;
public:
double GetProp1(void) {return mProp1;}
double GetProp2(void) {return mProp2;}
String tStep(void) {return L"";} // add your code here
};
class NodeRow : public std::vector<Node>
{
public:
void Print(std::ostream& output)
{
iterator i;
String tStr;
for(i = begin(); i != end(); i++)
tStr += /*to_string_with_precision(*/i->tStep()/*, 1)*/;
output << tStr.c_str() << L"rn";
}
};
class Node2D : public std::vector<NodeRow>
{
public:
void Print(std::ostream& output = std::cout)
{
iterator i;
for(i = begin(); i != end(); i++)
i->Print(output);
}
};
相关文章:
- 将对象放入地图后打印对象
- 打印对象的映射,其中另一个对象作为键
- 如何在C++中打印对象向量的内容
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- 使用成员函数打印对象
- 如何在C++中转换可打印对象中的对象
- 打印对象矢量的意外输出
- 如何使用 is_invocable() 创建用于重载<<打印对象的模板?
- 运算符重载<<,打印对象矢量时遇到问题
- 我正在尝试循环浏览对象的向量并打印对象的每个元素
- 在更改对象值后,打印对象数组仍会给出相同的值
- 声明并使用静态列表来打印对象(在c++中)
- 为什么写入临时字符串流对象只打印对象地址
- 打印对象数组
- 有没有一种方法可以打印对象的位表示
- OpenCV - 仅在绘制单应性时打印对象名称
- 在矢量 C++ 中可视化打印对象中的对象
- 使用 cout 打印对象指针值时地址长度不同
- C++模板打印对象名称
- 使用 c++ 中的重载运算符<<打印对象的动态数组