gpt4 book ai didi

c++ - 在类外声明 C++ 方法?

转载 作者:行者123 更新时间:2023-11-28 06:23:32 25 4
gpt4 key购买 nike

我的情况是我有一个 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) \
{ \
.... \
} \

但是因为它们没有与类一起声明,所以编译器拒绝构建(“错误:类没有成员”)。

最佳答案

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

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

这是一个例子:

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

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

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

关于c++ - 在类外声明 C++ 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com