关于宏标示符粘贴的一道题
#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;
}