Static Cast to access the static const class element

So, yesterday I looked at SO and could not find the answer to the following. This situation came from some code that I am working with, but here is MCVE to demonstrate it.

I have a class A defined in Ah that has only one static const in it. I already initialized it in the header.

#ifndef A_H_
#define A_H_
class A {
public:
    static const int test = 5;
    ~A(){};
};


#endif /* A_H_ */

Then I have class B, which needs to access the static const const from class A. In this example, it will deeply copy the value into the vector.

#ifndef B_H_
#define B_H_

#include "A.h"
#include <vector>
#include <iostream>

class B {
private:
    std::vector<int> testVec;

public:
    B(){

        testVec.push_back((const int)A::test);
        //testVec.push_back(static_cast<const int>(A::test)); //Also works
        //testVec.push_back(A::test); //Doesn't work without forward declaration of const int A::test in main or in this header 
        //(Compiler link error: undefined reference to `A::test')  
        std::cout<< testVec.front() << std::endl;
    }

    ~B(){};
};

#endif /* B_H_ */

Then basically I just call the constructor of class B.

#include "B.h"

int main() {

    B b;

    return 0;
}
//Does the cout from ctor of B and prints 5 to the screen. 

: , ​​. extern, . , ? ( , ).

:

Invoking: Cygwin C++ Linker
g++  -o "S_Test_p1.exe"  ./src/S_Test_p1.o   
./src/S_Test_p1.o:S_Test_p1.cpp:(.rdata$.refptr._ZN1A4testE[.refptr._ZN1A4testE]+0x0): undefined reference to `A::test'
collect2: error: ld returned 1 exit status
make: *** [makefile:47: S_Test_p1.exe] Error 1

: , , A:: test B.h( , ). , . - . , ?

+4
3

static static const int test = 5; , , . . const int A::test; ( " ".)

, static const , , ( ).

void std::vector<int>::push_back(const int&);. , A::test .

, (const int)A::test static_cast<const int>(A::test), int A::test, . A::test .

++ 17, A::test , static inline .

static *.cpp , , .

+7

1:

struct A { static const int value = 5; };
struct B { const int& n ; B() : n(A::value) {} };

int main()
{
    B b;
}

, A::value ( ). :

main.cpp:(. text._ZN1BC2Ev [_ZN1BC5Ev] + 0xf): undefined `A:: value '

, :

struct A { static const int value = 5; };
struct B { const int& n ; B() : n(A::value) {} };
const int A::value;

int main()
{
    B b;
}

1) A::test (. std::vector::push_back(). B A::value.

+1

, .

#include "B.h" main "B.h". , #include "A.h" "B.h" "A.h". "A.h" A , A::test. ( ), .

The binding problem is that you must also define a static member. Usually you will have a .cpp file that has class member function definitions. This file must also define a static member:

const int A::test;
0
source

Source: https://habr.com/ru/post/1687723/


All Articles