类的静态成员 及 private修饰的静态成员 的使用方法小结

本文详细介绍了C++中类的静态成员变量和静态成员函数的使用方法,包括它们的声明、定义、访问规则以及在类内外的调用方式。通过具体的代码示例,阐述了public和private静态成员的区别,以及static方法的特性和限制。

类的静态成员及private修饰的静态成员的使用方法小结

- 静态成员变量在类中仅仅是声明,没有定义,所以要在类的外面定义,实际上是给静态成员变量分配内存;

- 静态成员函数和静态数据成员,定义时,不需要加static修饰符,否则会报错:"Cannot declare member function ...to have static linkage";

public方法可访问static成员;static方法只能访问static成员

- 在pubic方法中,static成员可以用this指针访问(默认隐去this指针);static方法中不能使用this指针

private修饰的静态成员函数和静态数据成员,只能在类的内部使用

 

测试代码:static_test.cpp,在相应代码后有注释说明。

#include <iostream>
using namespace std;
 
class test
{
public:
	int k;
	static int i;
	test() {k=0;}
	void print();
	void call_static_fun();
	static void print_j();
private:
	static int j;
};

int test::i = 0;
int test::j = 0;

//public方法访问static成员 
void test::print()
{
	cout << ">>: run  print() :" << endl;

	cout << "print() i = "<< i << endl;
	cout << "print() j = "<< this->j << endl;//此处加不加this都可以
	print_j();
	
}
 
//static方法访问static成员 
void test::call_static_fun()
{
	cout << ">>: run  call_static_fun() :" << endl;

	cout << "call_static_fun() j = "<< j << endl;
	this->print_j();
}

//static方法访问public测试
void test::print_j()
{
	cout << ">>: run  print_j() :" << endl;
	// cout << "print_j():k = "<< this->k << endl;//错误!!!static方法中没有this指针
	// cout << "print_j():k = "<< k << endl;//错误!!!static方法只能访问static成员
	//print();//错误!!!static方法只能访问static成员
}


int main()
{
	test t;
	t.print();
	t.call_static_fun();


	cout << "main : i = "<< t.i << endl;//static数据成员的访问
	//cout << "j = "<< t.j << endl;//错误!!! private修饰的static成员不能在类外访问
	test::print_j();//static方法的访问
	t.print_j();//static方法的访问
	
	return 0;
}

g++ -o staic_test.o static_test.cpp 

输出:

yuan@linx-c:~/VSCode/CPP_Learning/static_test$ ./staic_test.o 
>>: run  print() :
print() i = 0
print() j = 0
>>: run  print_j() :
>>: run  call_static_fun() :
call_static_fun() j = 0
>>: run  print_j() :
main : i = 0
>>: run  print_j() :
>>: run  print_j() :

注释部分相关报错

error: ‘this’ is unavailable for static member functions
  cout << "print_j():k = "<< this->k << endl;

error: invalid use of member ‘test::k’ in static member function
  cout << "print_j():k = "<< k << endl;


error: cannot call member function ‘void test::print()’ without object
  print();

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值