声明和带有定义的声明。为什么不允许这样做?
Declaration and declaration with definition. Why is this not allowed?
我想知道,为什么不允许写:
struct foo {
void bar(); // declaration
void bar(){std::cout << "moo" << std::endl;} // declaration + definition
};
函数声明了两次(我觉得这样就可以了)定义了一次。但是,我的编译器抱怨:
decldef.cxx:7:10: error: 'void foo::bar()' cannot be overloaded
为什么不允许?
为什么我的编译器 (g++ 4.7.2) 将此解释为重载?
PS:我知道怎么写"the correct way",但我就是想知道为什么上面写错了
来自§9.3
Except for member function definitions that appear
outside of a class definition, and except for explicit specializations of member functions of class templates
and member function templates (14.7) appearing outside of the class definition, a member function shall not
be redeclared.
此外,在这种情况下,这些陈述还可能违反:
A member function may be defined (8.4) in its class definition, in which case it is an inline member function
(7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined
in its class definition.
由于第一个声明没有声明函数为inline
。第二个定义隐含。
不过,仔细一想似乎不太有说服力。
The function is declared twice (I thought this is ok) and defined once.
这与您是否第二次定义函数无关。关键是你声明函数两次,那就是不OK。
这也不编译,有同样的错误信息:
struct foo {
void bar();
void bar();
};
您不能 re-declare class 定义中具有相同参数列表的相同函数:
'void foo::bar()' cannot be overloaded with 'void foo::bar()'.
我想知道,为什么不允许写:
struct foo {
void bar(); // declaration
void bar(){std::cout << "moo" << std::endl;} // declaration + definition
};
函数声明了两次(我觉得这样就可以了)定义了一次。但是,我的编译器抱怨:
decldef.cxx:7:10: error: 'void foo::bar()' cannot be overloaded
为什么不允许?
为什么我的编译器 (g++ 4.7.2) 将此解释为重载?
PS:我知道怎么写"the correct way",但我就是想知道为什么上面写错了
来自§9.3
Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.
此外,在这种情况下,这些陈述还可能违反:
A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.
由于第一个声明没有声明函数为inline
。第二个定义隐含。
不过,仔细一想似乎不太有说服力。
The function is declared twice (I thought this is ok) and defined once.
这与您是否第二次定义函数无关。关键是你声明函数两次,那就是不OK。
这也不编译,有同样的错误信息:
struct foo {
void bar();
void bar();
};
您不能 re-declare class 定义中具有相同参数列表的相同函数:
'void foo::bar()' cannot be overloaded with 'void foo::bar()'.