C++提供了三種訪問類或者類對象的操作符,他們是 雙冒號 ::
, 點 .
, 箭頭 ->
, 這三種操作符有着各自的使用場景和定義。
雙冒號 ::
A::B, ::
表示作用域運算符, A一定是一個類的名稱或命名空間的名稱, 僅僅用於當B是A類/A命名空間的一個成員的情況.
點 .
A.B, A爲一個實例化的類(也就是對象)或者結構體, B爲A的一個成員.
箭頭 ->
a->b, 是指針指向其成員的運算符, 等價於 (*a).b
,A 是指向結構體或者類的指針, B是A中的成員.
代碼舉例
#include<iostream>
int Num=3;
class Student
{
public :
void setid(int ID);
int getid(void);
Student();
private:
int id;
};
Student::Student(void) //::可以實現在類體外構造函數
{
std::cout << "Object is being created" << std::endl;
}
int Student::getid(void) //::可以實現在類體外定義其成員函數
{
return id;
}
void Student::setid(int ID)
{
id = ID;
}
int main()
{
Student a;
Student *b;
int Num=4;
a.setid(11); //.對象調用類的函數
b->setid(12);
std::cout<<a.getid()<<std::endl; //. 訪問對象a的成員函數getid()
std::cout<<b->getid()<<std::endl; //. 訪問指針b的成員函數getid()
std::cout<<::Num<<std::endl; //::可以使用全局變量, 此處輸出爲3
std::cout<<Num<<std::endl; // 此處輸出應該爲4
return 0;
}
輸出爲:
Object is being created
11
12
3
4