简体   繁体   中英

definition of static class function outside of class definition

Consider the followin simple class definition -

    // file A.h
#include <iostream>
class A {
public:
  static int f();
  static const int aa;
};


    // file A.cpp
#include "a.h"
using namespace std;
const   int A::aa = 10;
int A::f() {
    return A::aa;
}

And this is my main file -

    // main.cpp file
#include "a.h"
#include "b.h"
using namespace std;
const int A::aa = 100;
int A::f();
int main() {
    cout << A::aa << "\n";
    cout << A::f() << "\n";
}

When I try to compile main.cpp, the compiler complains that the declaration of A::f() in main.cpp outside the class is a declaration, not a definition. Why is this? I do not intend to define A::f() in main.cpp. It is defined in A.cpp and the linker should link the declaration of A::f() in main.cpp with its definition in A.cpp. So I do not understand why am I getting this error. Note this is a compilation error.

C++11 standard §9.3 [class.mftc] p3 :

[...] 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 .

Aside from that, you'll get a linker error due to multiple definitions of A::aa , but it seems that you expected that, judging from your last sentence.

The class and it's members are already defined, you just have to include the file into your main (which you've done). You do not need to declare or redefine it.

在第二个剪辑中,你不应该声明A的方法。

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