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

被折叠的 条评论
为什么被折叠?



