使用成员函数打印对象

Using Member Functions to Print Object

本文关键字:打印 对象 函数 成员      更新时间:2023-10-16

我有一个类,它包含一个由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);
}
};