【问题标题】:Dynamically Access Variable Inside a Struct C++在结构 C++ 中动态访问变量
【发布时间】:2021-09-22 16:22:01
【问题描述】:

我是 C++ 新手,对如何处理这个问题非常困惑。在 Javascript 中,我可以做这样的事情来非常轻松地动态访问对象:

function someItem(prop) {
    const item = {
        prop1: 'hey',
        prop2: 'hello'
    };
    return item[prop];
}

在 C++ 中,我假设我必须使用 Struct,但在那之后,我陷入了如何动态访问 struct 成员变量的问题。

void SomeItem(Property Prop)
{
    struct Item
    {
        Proper Prop1;
        Proper Prop2;
    };
    // Item[Prop] ??
 }
       

这可能是糟糕的代码,但我对如何处理这个问题感到非常困惑。

【问题讨论】:

  • Javascript 中的对象更类似于 C++ 中的std::unordered_map<std::string, sta::any>,而不是实际的 C++ 对象。
  • 对于您的结构,您声明了一个类型。您没有实例,因此无法访问非静态成员变量。
  • 建议替代方案有点困难,因为我认为我们需要更多上下文。
  • 旁注:几乎任何东西的动态访问都是有代价的。 C++ 就是要尽可能降低成本。为了确保您接受或至少理解您所做的事情对性能有影响,您通常必须提出要求,这通常意味着您自己编写。
  • 我的用例非常简单,但是,这非常有用。谢谢大家

标签: c++ object struct dynamic


【解决方案1】:

这是一个如何创建struct 实例然后访问其成员的简单示例:

#include <iostream>
#include <string>

struct Item {
    std::string prop1 = "hey";
    std::string prop2 = "hello";
};

int main() {
    Item myItem;
    std::cout << myItem.prop1 << std::endl; // This prints "hey"
    std::cout << myItem.prop2 << std::endl; // This prints "hello"
    return 0;
}

正如 cmets 中所述,您可能需要一张地图。地图具有与之关联的键和值,例如,您可以将键 "prop1" 与值 "hey" 关联:

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, std::string> myMap;
    myMap["prop1"] = "hey";
    myMap["prop2"] = "hello";
    std::cout << myMap["prop1"] << std::endl; // This print "hey"
    std::cout << myMap["prop2"] << std::endl; // This print "hello"
    return 0;
}

第一个在 C++ 中被认为是“正常的”struct 用法,另一个更适用于您必须通过键查找内容的情况

【讨论】:

  • 在第二个示例中,请注意使用[] 读取元素会导致元素在缺失时被插入。如果你使用.at(),你会得到一个缺少元素的异常。
【解决方案2】:

正如评论中提到的,在 C++ 中,您不会为此定义自定义结构,而是使用std::unordered_map。我不知道 Javascript,但如果 Property 是一个枚举(它可能是稍作修改的其他东西)并且 return item[prop]; 应该返回一个字符串,那么这可能很接近:

#include <string>
#include <unordered_map>
#include <iostream>

enum class Property { prop1,prop2};

std::string someItem(Property p){
    const std::unordered_map<Property,std::string> item{
        {Property::prop1,"hey"},
        {Property::prop2,"hello"}
    };
    auto it = item.find(p);
    if (it == item.end()) throw "unknown prop";
    return it->second;
}

int main(){
    std::cout << someItem(Property::prop1);
}

std::unordered_map 确实有一个operator[],你可以像return item[p]; 一样使用它,但是当没有找到给定键的元素时,它会在映射中插入一个元素。这并不总是可取的,当地图为const 时也不可能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多