gpt4 book ai didi

c++ - 在类定义之外定义静态类函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:46 24 4
gpt4 key购买 nike

考虑以下简单的类定义 -

    // 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++11 标准 §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.

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

关于c++ - 在类定义之外定义静态类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com