C++ 对静态函数的未定义引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17727681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:23:45  来源:igfitidea点击:

undefined reference to a static function

c++

提问by xenom

I have a strange problem when I create a static function in class A and I want to call it from class B function. I get

当我在 A 类中创建一个静态函数并且我想从 B 类函数中调用它时,我遇到了一个奇怪的问题。我得到

undefined reference to `A::funcA(int)'

对`A::funcA(int)'的未定义引用

Here is my source code : a.cpp

这是我的源代码:a.cpp

#include "a.h"

void funcA(int i) {
    std::cout << i << std::endl;
}

a.h

#ifndef A_H
#define A_H

#include <iostream>

class A
{
    public:
        A();
        static void funcA( int i );
};

#endif // A_H

b.cpp

b.cpp

#include "b.h"

void B::funcB(){
    A::funcA(5);
}

and b.h

和 bh

#ifndef B_H
#define B_H
#include "a.h"

class B
{
    public:
        B();
        void funcB();
};

#endif // B_H

I'm compiling with Code::Blocks.

我正在使用 Code::Blocks 进行编译。

回答by Nbr44

#include "a.h"

void funcA(int i) {
    std::cout << i << std::endl;
}

should be

应该

#include "a.h"

void A::funcA(int i) {
    std::cout << i << std::endl;
}

Since funcAis a static function of your class A. This rule applies both to static and non-static methods.

因为funcA是你的类的静态函数A。此规则适用于静态和非静态方法。

回答by JBL

You forgot to prefix the definition with the class name :

您忘记在定义前加上类名:

#include "a.h"

void A::funcA(int i) {
     ^^^
//Add the class name before the function name
    std::cout << i << std::endl;
}

The way you did things, you defined an unrelated funcA(), ending up with two functions (namely A::funcA()and funcA(), the former being undefined).

你做事的方式,你定义了一个不相关的funcA(),最后得到两个函数(即A::funcA()and funcA(),前者未定义)。