在C ++中将字符串/字符转换为类成员/方法 [英] convert string/character to class member/method in c++

查看:56
本文介绍了在C ++中将字符串/字符转换为类成员/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将字符串或字符转换为类成员/成员函数以动态访问它们?

Is there a way to convert string or characters to class member/member functions to access them dynamically?

例如这个特定的代码,

 #include <iostream>
 #include <map>

 using namespace std;

 class agnt {
 public:
 int x, y;
 agnt(int a=0, int b=0) : x(a), y(b) {}
 };


 int main() {
      map<int,agnt> agntID;
      agnt temp;
      temp.x=1;
      temp.y=5;

      agntID[1]=temp;

      for(char tmp='x'; tmp<'z'; tmp++) {
         cout<<agntID[1].tmp<<'\n';     //Here I get the following error: tmp is
         }                              //not a member of class agnt
 }

是否有一种方法可以转换字符"tmp",使其被识别为类成员?任何提示或解决方案将不胜感激.

Is there a way to convert the character 'tmp' such that it is identified as a class member? Any tips or solution will be appreciated.

推荐答案

您无法在C ++中执行此操作,因为它是静态类型的语言.获得这种行为的一种方法是提供访问包装器:

You can't do this in C++ because it's a statically-typed language. One way to get this sort of behaviour is to provide accessing wrappers:

template <char c>
struct getter {
};


template <>
struct getter<'x'> { 
   static int get(const agnt &theAgnt) {
      return theAgnt.x;
   }
};


template <>
struct getter<'y'> { 
   static int get(const agnt &theAgnt) {
      return theAgnt.y;
   }
};

template <char c>
int get(const agnt &theAgnt) {
    return getter<c>::get(theAgnt);
}

然后致电:

agnt temp;
//... set members
std::cout << get<'x'>(temp) << std::endl;

但是, for 循环无法按您期望的方式工作,因为模板参数需要在编译时确定.另外,您不能只请求任何旧的东西,除非您在非专门的 getter 中定义了一个 get 函数,该函数会返回某种NULL指示符,例如 INT_MIN.

However, the for loop won't work the way you expect, because the template parameters need to be determined at compile time. Also, you can't just request any old thing, unless you define a get function in the unspecialised getter which returns some sort of NULL-indicator, like INT_MIN.

但是 ,这实际上是一种获取模糊与动态语言类似的东西的工具.但这与仅引用 temp.x 并没有什么不同.相反,您应该尝试遵守C ++约定并享受静态输入!

However, this is all really a hack to get something vaguely similar to a dynamic language. But it's not really anything different from just referencing temp.x. Instead, you should try to adhere to C++ conventions and enjoy the static typing!

这篇关于在C ++中将字符串/字符转换为类成员/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆