2017-08-24 70 views
0

我有一个类,其中包含由vector< vector<Node> >实现的树结构,其中Node包含一组通过getters/setter公开的属性。使用成员函数打印对象

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); 

     ... 

有一些华而不实/方便/面向对象推广这一功能的方式,以便它可以打印出任何节点的属性(而不仅仅是吐出硬连线的tstep()属性,或者通过if/then语句实质上做同样的事情)。

我做过的事情这在C中使用函数指针,但这是C++和C++常见问题解答说不要乱指向成员函数的指针。

+1

你真的想要什么(我认为)是“反射” - 这还不是C++标准的一部分。 : - /这可能会让你感兴趣:https://meetingcpp.com/index.php/br/items/reflections-on-the-reflection-proposals.html –

+0

寻求调试帮助的问题(“为什么这段代码不工作? “)必须包含所需的行为,特定的问题或错误以及在问题本身中重现问题所需的最短代码。没有明确问题陈述的问题对其他读者无益。请参阅:如何创建[mcve]。使用“编辑”链接来改善你的*问题* - 不要通过评论添加更多信息。谢谢! – GhostCat

回答

0

你可能想模板函数:

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() << " "; 
    }); 
} 
0

1日运你环路忽略的第一要素。 vector是基于零的,并且您正在使用++t++state,这会增加循环顶部的值。这意味着你永远不会访问第0个元素(mGrid[0]mGrid[t][0])。
第二,你没有包括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"\r\n"; 
    } 
}; 

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); 
    } 
}; 
+0

我不同意。控制变量在底部进行测试。使用前或后增量无关紧要。看到https://stackoverflow.com/questions/4706199/post-increment-and-pre-increment-within-a-for-loop-produce-same-output – Mathematician

+0

@Mathematician我说的是它第一次进入循环。当你到达'[]'运算符时,'t'和'state'的值是1而不是0.测试部分是正确的。你写的代码跳过了第0个元素。至少你应该使用't ++'和'state ++'。只要调试代码,你会看到我在说什么。 – Sam

+0

@Mathematician也要记住迭代器比索引好得多(更快)。 – Sam