C++为什么类成员函数不能重新声明,但普通函数可以

C++ why class member function cannot be redeclared but normal function can

本文关键字:函数 声明 成员 为什么 不能 C++ 新声明      更新时间:2023-10-16
void say();
void say();  // ok
class Test{
void say();
void say(); // error class member cannot be redeclared
};

这是因为类成员函数声明分配内存,以便编译器不允许重新声明吗?提前谢谢。

你可以用 c++ 多次声明内容(只要它们都是一样的(。您只能定义一次事物。

在类成员声明的情况下,虽然您声明了某些内容,但实际上您正在定义类成员,并且不允许声明同一成员两次。如果我们使用变量而不是函数,那么规则存在的原因就更明显了:

extern int a;
extern int a; //  just a redeclaration, that's fine
struct B
{
int b;
int b; // not allowed, is this a second member also called b or is it a redeclaration of the existing member?
};