简体   繁体   中英

Declare, then define a class method - Why an error?

Why doesn't this compile?

class Test
{
    void foo();
    void foo()
    { }
};

But these will compile:

void bar();
void bar()
{ }

// In same header/file
class Test
{
    void foo();   
};
void Test::foo()
{ }

The compiler would say that given method cannot be overloaded . The method Test::foo is not being overloaded - it is the same function with exact same signature.

It's explicitly prohibited by the C++ standard. Right there at [class.mfct/1]

A member function may be defined in its class definition, in which case it is an inline member function, or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition. 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 ([temp.spec]) appearing outside of the class definition, a member function shall not be redeclared.

It is just the way it is in C++. Redeclaring a class member is not allowed (unless you consider an out-of-class definition as another declaration ). Redeclaring a namespace member is OK as long as you obey ODR.

Why doesn't this compile?

class Test {
  void foo();
  void foo() { }; // wrong
};

Because, as StoryTeller and others answered, you are declaring and defining the same member function void Test::foo(void) twice (and the inside-class definition of foo is implicitly inline ).

If you want to define a member function in your header file after the class, you'll better declare it explicitly as inline like this:

class Test {
   inline void foo();
};

and later define that member function (eg below in the same header file):

void Test::foo() {
  // body of Test::foo
}

BTW, if you declare a member function with outside definition like above, and that member function is not inline but is defined in some header file which is included in several translation units, that function would be multiply defined and the linker would complain.

void foo();

and

void foo() {}

are two ways of declaring functions in a class definition. The first only declares the function and the second declares the function and also implements it. Therefore the compiler assumes that you are going to re-declare the same function and is not a correct overload as the function signature is the same in both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM