欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++静态变量

程序员文章站 2024-02-21 17:05:04
...

类继承的过程中静态变量共享的,无论是静态成员变量还是成员函数中的静态变量

#include <boost/filesystem.hpp>
#include <string>
#include <fstream>
#include <iostream>

class Parent {
public:
	Parent() = default;
	~Parent() = default;
	int counter() {
		static int a(0);
		return a++;
	}

	static int b;
};

int Parent::b = 0;

class Sun: public Parent {
public:
	Sun() = default;
	~Sun() = default;
};

class Daughter: public Parent {
public:
	Daughter() = default;
	~Daughter() = default;
};

int main() {
	Parent parent;
	Sun sun;
	Daughter daughter;

	std::cout << "Test of static variable in member function" << std::endl;
	std::cout << parent.counter() << std::endl;
	std::cout << sun.counter() << std::endl;
	std::cout << daughter.counter() << std::endl;

	std::cout << "Test of static member variable" << std::endl;
	std::cout << parent.b++ << std::endl;
	std::cout << sun.b++ << std::endl;
	std::cout << daughter.b++ << std::endl;

	return 0;
}

输出

Test of static variable in member function
0
1
2
Test of static member variable
0
1
2

 

相关标签: C++基础