在课堂外声明C ++方法?

时间:2015-03-08 15:15:58

标签: c++ macros

我的情况是我有一个带有宏的C ++文件,可以动态生成多个函数:

#define FUNC_GEN(x,y,z) \
int x(int arg1, float arg2) \
{ \
    .... \
} \
\
int y(int arg1, int arg2, int arg3) \
{ \
    .... \
} \
\
double z(int arg1, float arg2) \
{ \
    .... \
} \

FUNC_GEN(func1,func2,func3) // Hundreds of these

这会生成如下内容:

int func1(int arg1, float arg2)
{
    ....
}

int func2(int arg1, int arg2, int arg3)
{
    ....
}

double func1(int arg1, float arg2)
{
    ....
}

我有数百个分散在整个文件中。我想要做的是更改FUNC_GEN以生成特定类的生成函数方法。我遇到的问题是我的理解是必须使用类定义声明函数。因为这实际上是在动态生成函数,所以在类定义中插入这些函数并不容易。

在C ++中是否有办法更改此宏以使这些方法成为类成员?我只知道一种方法(我避免的那种方式),即追捕所有这些宏并手动将它们自己添加到类定义中。

我天真的做法就是这样做:

#define FUNC_GEN(x,y,z) \
private int myclass::x(int arg1, float arg2) \
{ \
    .... \
} \
\
private int myclass::y(int arg1, int arg2, int arg3) \
{ \
    .... \
} \
\
private double myclass::z(int arg1, float arg2) \
{ \
    .... \
} \

但是因为它们没有在类中声明,所以编译器拒绝让这个构建("错误:类没有成员")。

3 个答案:

答案 0 :(得分:1)

也许最简单的解决方案是定义类中的函数:

class myclass
{
  private:
  FUNC_GEN(func1,func2,func3) // Hundreds of these
};

答案 1 :(得分:0)

所有成员函数的声明必须包含在类定义中。你可以:

  • 使用宏或

  • 定义类声明中的函数
  • 创建另一个只会声明函数但不定义它们的宏,并将其放在类声明中。

答案 2 :(得分:0)

类方法的定义可以在类之外的任何地方。在类外部定义类方法时,需要在方法名称前加上类名称和范围解析运算符。

重要的一点是不要使用范围访问关键字,例如privateprotectedpublic

以下是一个例子:

class Kitten
{
  public:
    void run ();
    void hiss ();
};

void Kitten::run()
{
  //...
}

void Kitten::hiss()
{
  //...
}
相关问题