C++中的static、const与类、成员变量成员函数分开存储

C++中的static、const与类、成员变量成员函数分开存储,第1张

static

都知道static在C语言中的作用,这里回顾一下:

  1. static修饰局部变量时会延长变量的生命周期。
  2. static修饰全局变量和函数时 对外部隐藏,只能在本文件访问。
  3. static修饰的变量只能初始化一次,不初始化时默认值为0.

那么C++中static有哪些特性呢?
首先应该知道C++是完全兼容C的,所以static在C中的特性可以延用。
但是C++中的static与类搭配使用时会有一些新 *** 作。

static修饰成员变量

static 修饰成员变量在编译时期分配内存空间。

class Person {

public:
	Person() 
	{
	}
	Person(int age, int h)
	{
		this->age = age;
		this->h = h;
	}

public:
	int age;
	static int h;
};
int Person::h = 0; // 类内声明,类外定义初始化

int main()
{
	cout << sizeof(Person) << endl; // 打印 4 因为静态成员变量不占用类空间

	Person p(1,2); // Peoson对象将静态成员变量 h 设置为2
	cout << p.h << endl;

	Person p2;
	cout << p2.h << endl; // 打印 2 ,因为俩个对象共享同一个 h

	return 0;
}
static 修饰成员函数
class Person {

public:
	Person() 
	{
	}
	Person(int age, int h)
	{
		this->age = age;
		this->h = h;
	}

	static void test() 
	{
		h = h+1; // 静态函数中只能访问静态成员变量
	}

public:
	int age;
	static int h;
};


int Person::h = 0;

int main()
{
	Person p; // Peoson对象将静态成员变量 h 设置为2
	p.test(); // 对象p调用静态的test成员函数使得h变为1

	Person p2;
	p2.test(); // 使得h变为2;因为所有对象共享同一个静态函数。

	cout << Person::h << endl; //打印2

	Person::test(); // 静态成员不占用类空间,不属于任何对象,所有可以用作用域的方式调用

	cout << Person::h << endl; // 打印3

	return 0;
}

总结

静态成员

static修饰的成员变量:

  1. 被所有对象共享,编译阶段分配内存空间。
  2. 类内声明,类外初始化。

static修饰成员函数

  1. 该函数被称为静态成员函数。
  2. 静态成员函数中不能访问任何非静态的成员,但是非静态成员函数可以访问静态成员。
  3. 静态成员函数中没有this指针。
const修饰成员函数

本质上还是修饰成员函数中的隐式形参this指针。

class temp {

public :
	// const修饰this指针,因为是隐式的形参,所以只能写在函数后面
	// 此时 编译器会将this指针变为 (const temp * const this)
	void test(int age) const 
	{	// 这里的形参实际上有两个  一个 指向对象首地址的this指针,一个就是age
		
		cout << "test22" << endl;
	}
	void test(int age) 
		// 这里发生了重载,因为这个函数的形参是 ( temp * const this, int age)
		// 与上面test函数的形参列表不同函数名相同,所以符合重载条件
	{
		cout << "test11" << endl;
	}

public:
	int age;
	int h;
};

int main()
{
	temp t1;
	const temp t2;

	int age = 10;

	t1.test(age); // 打印 test11
	t2.test(age); // 打印 test22

	return 0;
}
成员变量成员函数分开存储

C++类中属于类空间的只有非静态成员变量

class temp {

public:
	static void test1() // 单独存储,不占用类空间
	{
	
	}
	void test2() // 单独存储,不占用类空间
	{

	}

public:
	int age;
	static int h; // 不占用类空间,编译时分配空间
};
int main()
{
	cout << sizeof(temp) << endl; // 4

	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/914947.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存