How I can access a private static member variable via the class constructor? [duplicate]

StackOverflow https://stackoverflow.com/questions/23324433

  •  10-07-2023
  •  | 
  •  

Domanda

How can I use and modify the s_member private static variable from the constructor or in general from an other member function?

This is what I tried.

a.h:

#ifndef A_H
#define A_H

#include <set>

class A
{
    public:
        A();
        virtual ~A();

    private:
        static std::set<int> s_member;
};

#endif

a.cpp:

#include "a.h"

A::A()
{
    A::s_member.insert(5); // It causes error.
}

I get this error:

/tmp/ccBmNUGs.o: In function `A::A()': a.cpp:(.text+0x15): undefined
 reference to `A::s_member' collect2: error: ld returned 1 exit status
È stato utile?

Soluzione

You have declared A::s_member but not defined it yet. To define it, put below code, outside of class:

std::set<int> A::s_member;

For example:

std::set<int> A::s_member;

A::A()
{
  // ...
}

The problem is not related to accessing and private/public.

Altri suggerimenti

You have to define the variable

#include "a.h"

std::set<int> A::s_member;

A::A()
{
    A::s_member.insert(5); // It causes error.
}

The reference to object file ccBmNUGs.o in the error message says that it is an error of the linker. The linker can not find the definition of s_member

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top