关于宏标示符粘贴的一道题

superdesolator 2014-03-13 04:34:08
#define FIELD(a) char* a##_string;int a##_size
class A {
FIELD(one);
FIELD(two);
FIELD(three);
//..
};
这是原来的宏,展示的功能是标示符粘贴,下面是问题,我不知道这个问题该怎么做
Modify the FIELD( ) macro so that it also contains an index number. Create a class whose members are composed of calls to the FIELD( ) macro. Add a member function that allows you to look up a field using its index number. Write a main( ) to test the class.
我不懂怎么包含一个index numer,然后可以通过类的成员函数去根据这个index查看一个filed???

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
下面附带一个是紧接着这个练习的另一个练习问题和官方答案,大家可以看看,但我的问题就是上面的问题
Modify the FIELD( ) macro so that it automatically generates access functions for each field (the data should still be private, however). Create a class whose members are composed of calls to the FIELD( ) macro. Write a main( ) to test the class.

Solution:

//: S09:FieldAccessors.cpp
#include <iostream>
#include <string>
using namespace std;

#define FIELD(type, name) \
private: \
type name ## _; \
public: \
type name() const {return name ## _;} \
void name(type val) {name ## _ = val;}

class C {
FIELD(int, foo);
FIELD(float, bar);
FIELD(string, baz);
};

int main() {
C c;
c.foo(1);
c.bar(2.0);
c.baz("three");
cout << c.foo() << endl;
cout << c.bar() << endl;
cout << c.baz() << endl;
}
...全文
41 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

65,209

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧