【问题标题】:How to access user-chosen struct variable C++如何访问用户选择的结构变量 C++
【发布时间】:2021-10-07 10:43:06
【问题描述】:

我正在使用一个函数从链表中打印数据,链表节点有 2 个可以访问的变量,数据或索引。我想向 print() 函数添加一个参数,允许用户在节点中调用他们想要输出的变量名称,我听说过通过引用传递,我很确定这就是我想要的做,但还没有找到任何真正适用于我的代码的资源。

(只是我想将变量名传递给函数)。

这是我的代码:

struct Node {
    int data;
    int index;
    Node *next;
}

Node *_current;
Node *_next;
Node *_head;
Node *_temp;
Node *_tail;
Node *_last;
// all this is handled correctly

void print(*variable name*) {
   Node *n = _head;
   while (n->next != nullptr) {
       std::cout << n-> *variable name* << std::endl;
       n = n->next;
   }
}

p.s:变量名不一定是指针,而只是(字面意思)引用我要添加的变量名参数。

如果我将 variable name 换成 'std::cout data

非常感谢任何有用的信息,在此先感谢您。 :)

【问题讨论】:

    标签: c++ struct pass-by-reference


    【解决方案1】:

    p.s:变量名不一定是指针

    但它是一个指针。一个成员指针,具体来说:

    void print(int Node::*member) {
       Node *n = _head;
       while (n->next != nullptr) {
           std::cout << n->*member << std::endl;
           n = n->next;
       }
    }
    

    它会被调用为任一

    print(&Node::data);
    

    print(&Node::index);
    

    【讨论】:

    • 非常感谢山姆,这以我想要的方式解决了我的问题! :),祝你有美好的一天。
    • 为了超级技术,成员指针不是指针,尽管它们被称为:)
    【解决方案2】:

    你可以传入一个字符串。

    void print(const string& str) {
    
       Node *n = _head;
       if(str.compare("index")==0){
           while (n->next != nullptr) {
               std::cout << n->index << std::endl;
               n = n->next;
           }
       }
       else if(str.compare("data")==0){
           while (n->next != nullptr) {
               std::cout << n->data << std::endl;
               n = n->next;
           }
       }
    
    }
    

    【讨论】:

    • 虽然是这样,但您也可以传入布尔值或枚举,并摆脱字符串比较。另外,使用比较比较字符串有点奇怪,而不是==
    • 这确实有效,但是我正在寻找一种可以无限期工作的解决方案,而无需使用大量的 switch/if,else 循环。为帮助欢呼
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    相关资源
    最近更新 更多