문제

There is class:

k.h

class k
{
    static int ii;
    static void foo();
};

k.cpp

#include "k.h"

void k::foo()
{
    ii++;
}

During compile I get the following error message:

error LNK2001: unresolved external symbol "private: static int k::ii" (?ii@k@@0HA)

It's OK. But when I add inline keyword to method, error is disappeared:

class k
{
    static int ii;
    inline static void foo();
};

This is not real-world example, but I don't know what exactly happens in this code, may be someone explain it to me?

도움이 되었습니까?

해결책

This code:

#include <iostream>
using namespace std;

struct k
{
    static int ii;
    static void foo();
};

void k::foo() {
    ii=0;
}

int main() {
    // your code goes here
    return 0;
}

gives a linking error, because the function k::foo is output by the compiler, and it references k::ii.

This code:

#include <iostream>
using namespace std;

struct k
{
    static int ii;
    inline static void foo();
};

inline void k::foo() {
    ii=0;
}

int main() {
    // your code goes here
    return 0;
}

does not give a linking error, because the function k::foo is declared inline and is not called from anywhere, so the compiler never actually produces any code for it.

If you add a call to k::foo() inside main, or anywhere else, then you will get a linking error.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top