類的靜態成員及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();