首先,我在stackoverflow上找了1个多小时,但我真的不知道,如何找到我要找的具体问题(我猜已经有一些答案了)。
我正在尝试通过变量(字符串)调用一个对象
我的代码示例:
//class itself
using namespace std
class locations {
public:
locations(int id, string name){ // constructor
this->id= id;
this->name=name;
}
int id= 0;
string name = "";
};
和新对象:
locations home(1,"home");
我现在想要的是这样的:
string obj = "home";
obj.id = 3;
或
string meth = "id";
home.meth = 3;
如果您有指向其他问题的任何好的链接,那将会很有帮助。
也许可以通过 vector 以某种方式访问它,但我对此了解不多
C++ 在设计时考虑了强类型和编译时检查和优化。没有针对您想要的访问类型的内置设施。
1) 动态查找对象:
C++ 不支持您期望的语义:
string obj = "home"; // create an object of type string.
obj.id = 3; // access to member id of your object.
如果它是动态的,生成的代码将需要维护变量的范围(因为 home 对象在不同的范围内可能有不同的含义。
但幸运的是,在 map 的帮助下,您可以轻松地实现一个对象存储,在其中注册您的对象及其名称。 :
map<string, locations> mystore; // store of all my location variables
mystore["home"] = locations(1,"home"); // copy a new object into the store
string obj = "home";
mystore[obj].id = 3; // access object via its name.
顺便说一下,如果 locations::name
只是为了通过名称提供访问权限,您将不再需要在 locations
中使用它,因为 map 链接了字符串到对象值。
2) 动态查找成员:
C++ 根本不支持你的语义:
string meth = "id"; // name of a member
home.meth = 3; // invalid: because meth is not a member of home
C++ 不支持您在 java 和其他半编译或解释语言中找到的反射。如果你需要这样的东西,你需要仔细设计你的类来自己实现它。这将相当困难,因为每个成员都可以有自己的类型,而 C++ 需要在编译时知道类型。
一种方法是结合使用 map (存储您的动态成员)和使用 boost::variant
(用于存储可以具有不同类型值的 map 对象)。
但这并不容易,最重要的是,您必须自己管理不同类之间的任何继承逻辑。