c++基础:7.类与static

class与struct的区别,class默认成员是私有的,struct默认成员的公共的。在只包含一些变量的情况下,尽量使用struct。如果有很多功能尽量使用class。

static 静态

类外使用static修饰的符号,在链接(link)阶段是局部的,只对定义它的编译单元(.obj)可见。
类内部使用static,表示这部分内存是这个类的所有实例所共享的。也就是不管实例化多少类对象,static修饰的变量只有一个实例。类内部的静态方法没有该实例的指针(this)。

类外静态变量

static修饰的变量或方法,链接器不会在这个编译单元(cpp)外找它的定义。

//test.cpp
#include 
static int s_Var = 10;

//demo.cpp
#include 
extern int s_Var;
int main()
{
	std::cout<<s_Var<<std::endl;
}

build会报link错误,去掉static才会成功build。

类外静态方法

//test.cpp
void fun()
{
}
//demo.cpp
void fun()
{
}
int main()
{	
	fun();
}

build是不通过的,因为链接的时候会发现test.cpp和demo.cpp这两个编译单元都有fun这个函数。将test.cpp 中的方法改为静态方法后build通过。

//test.cpp
static void fun()
{
}

总结:在类或结构体外定义一个静态函数或变量,意味着定义的函数和变量只对它的声明所在的cpp文件是可见的。

类内部的静态

1.所有类的实例对象,共享static修饰的变量。
2.静态方法不能访问非静态变量
3.如果一个类要求它全部的对象共享某一个数据,就要使用static修饰这个数据

//demo.cpp
#include 
class Test
{
	public:
	static int x;
	void print()
	{
		std::cout<<x<<std::endl;
	}
}
int Test::x=0;
int main()
{
	Test t1;
	Test t2;
	t1.print();
	t2.print()
	Test::x=10;
	t1.print();
	t2.print();
}
//结果
0
0
10
10

你可能感兴趣的:(c++基础,c++)