【发布时间】:2016-10-21 06:25:34
【问题描述】:
我想实现一个函数,可以通过它的名字打印出struct('Data')的一个成员变量(例如'aa')的值。 我尝试如下使用宏定义,但失败了。 有没有简单的实现方法?
#include <string>
#include <iostream>
using namespace std;
struct Data
{
int aa;
int bb;
int cc;
Data(): aa(1),bb(2),cc(3) {};
};
#define Param(a,b) a.##b
void Process(Data& data, const string& name)
{
cout << Param(data, name) << endl;
}
void main()
{
Data data;
Process(data, "aa");//I want print the value of Data.aa
Process(data, "bb");//I want print the value of Data.bb
Process(data, "cc");//I want print the value of Data.cc
}
【问题讨论】:
-
你可以在结构体中声明函数,就像在类中一样
-
只需调用带有参数
data.aa的过程函数 -
实际情况比这个复杂,不能直接调用。
-
不,C++ 没有提供一种简单的方法来实现这一点。事实上,据我所知,它根本无法实现这一点
标签: c++