How to dynamically call property names in C++ like square bracket notation in JS?

时间秒杀一切 提交于 2021-02-08 08:54:27

问题


My first language is Javascript, but I'm starting to learn C++. One of my favorite things to do is access properties with clever variable property names using square bracket notation in Javascript like so:

var a = "prop";
var obj = {
  this.prop : "before"
};
function alterObj(a){
  obj[a] = "after";
}

It doesn't seem to be coming up in my C++ books, and I'm having trouble Googling it. So how does one dynamically select property names in C++?


回答1:


The short answer is one cannot do this in c++. A major difference between c++ and javascript are that c++ is a compiled language whereas javascript is not. Javascript has a lot of neat runtime features that you can use, i.e. you can use bracket notation to access properties

obj["property"]

This allows any sort of string to be placed in the brackets and then evaluated at runtime. C++, however does not have as large of a runtime (there is a very powerful runtime, but powerful in a different way).

Now with all this said if you wanted to implement a function like your alterObj above you could use the map class. Also you can overload the [] operator. The following snippet gives an example:

#include <iostream>
#include <map>

class SpecialObject {
  public:
  std::string operator[](std::string key);
};

std::string SpecialObject::operator[](std::string key) {
  std::string retVal = key + " whoa!";
  return retVal;
}

void modify(std::map<std::string, std::string> &obj) {
  obj["something"] = "someone else";
}

int main(int argc, const char *argv[]) {
  std::map<std::string, std::string> obj;
  obj["something"] = "someone";
  modify(obj);
  std::cout << "obj[\"something\"] = " << obj["something"] << std::endl;

  SpecialObject obj2;
  std::cout << "obj2[\"The clowns say\"] = " << obj2["The clowns say"] << std::endl;
  return 0;
}

The map object allows you to create a simple container for other objects (in some sense exactly like what javascript objects are) and the SpecialObject class shows how you can implement the [] operator yourself.




回答2:


C++ is a compiled language. Most names of classes, variables, properties, enums and functions don't make it to the final binary, they are processed in compile time and translated into memory offsets to the final machine code to use.

Such named references are almost completely lost and can only be backtraced with debug data.

Long story short, there is no way you can do this in C or C++. But you can still work with pointers or use preprocessor macros.



来源:https://stackoverflow.com/questions/23962070/how-to-dynamically-call-property-names-in-c-like-square-bracket-notation-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!