【问题标题】:definition of static class function outside of class definition在类定义之外定义静态类函数
【发布时间】:2012-02-28 01:07:37
【问题描述】:

考虑以下简单的类定义 -

    // 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;
}

这是我的主文件 -

    // 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";
}

当我尝试编译 main.cpp 时,编译器抱怨在类外部 main.cpp 中的 A::f() 声明是声明,而不是定义。为什么是这样?我不打算在 main.cpp 中定义 A::f()。它在 A.cpp 中定义,链接器应将 main.cpp 中的 A::f() 声明与其在 A.cpp 中的定义链接。所以我不明白为什么我会收到这个错误。请注意,这是一个编译错误。

【问题讨论】:

  • 你为什么有那条线?
  • 这里没有包含它。发现问题了。

标签: c++


【解决方案1】:

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

[...] 除了出现在类定义之外的成员函数定义,并且除了出现在类模板和成员函数模板 (14.7) 之外的成员函数的显式特化类定义,不得重新声明成员函数

除此之外,由于A::aa 的多个定义,您会收到链接器错误,但从您的最后一句话来看,您似乎已经预料到了。

【讨论】:

    【解决方案2】:

    类及其成员已经定义,您只需将文件包含到您的主文件中(您已经完成)。您不需要声明或重新定义它。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-16
        相关资源
        最近更新 更多