简体   繁体   中英

Removing static member from a header

What the difference between a static member variable of a class and a "free" variable defined in the "body" of the class? I mean can I use the second in place of the first to discharge a header of the class?

// b.h
class B
{
public:
  B(int j);
  void print();
private:
  static int is;
};


//b.cpp
#include <iostream>

int i = 0;
int B::is = 0;

B::B(int j)
{
  i = j;
  is = j;
}

void B::print(){
  std::cout << i << " " << is << " " << std::endl;
}

//main.cpp
int main() {
  B b1(1);
  b1.print();
  B b2(2);
  b2.print();
  b1.print();
  return 0;
}

output:

1 1 
2 2 
2 2 

In your case, the difference is that the static member data can be accessed only by the class, as it is declared in the private section of the class, which may be desirable in some cases. The global i can be changed by anyone.

So if a variable is meant for the class only, and shouldn't be used by others, then having a static member data in the private section is a better solution. It gives you restricted access to the variable. Global variables are bad in general, as it gives unrestricted access to anyone.

Note that in your case, the global variable i has external linkage. In other files, one could simply declare as extern int i , and then can use i and modify it as well.

Even if you make it static global variable, to make it have internal linkage, it is not good as compared to static member data, because the static member data gives you some sort of idea that the variable is used by the class only, not by non-class members (if any in the same file). So static member data increases readability, in comparison to global static data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM