C++中“->”和“.和“::”的区别
First Post:
Last Update:
C++中“->”和“.和“::”的区别
1、**->**是指针指向其成员的运算符。
. 是结构体的成员运算符。
最大的区别是->前面放的是指针,而.前面跟的是结构体变量。
例如:
1 2 3 4 5 6 7 8 9
| struct A { int a; int b; }; A *point = malloc(sizeof(struct A)); point->a = 1; A object; object.a = 1;
|
2、**::**是域作用符,是各种域性质的实体(比如类(不是对象)、名字空间等)调用其成员专用的。
(如果有个局部变量与全局变量同名(假设都是int a;),默认调用的 a 是局部变量,如果要访问全局变量a,就要这么写“::a”。使用域作用符来加以区别;前面没写具体的域名,就是指默认域)
.是成员作用符,是对象专用的。
例如:
1 2 3 4 5
| struct A { int InnerPara; static int StPara; } a;
|
a访问时用“.”,如a.InnerPara;A访问用“::”,如A::StPara;
再例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include<iostream.h> int Num=3; class aa{ public : void a1(); static void a2(); private: static int id; }; void aa::a1() { cout<<"a1"<<endl; } void aa::a2() { cout<<id<<endl; } int aa::id=14; void main() { aa a; int Num=4; cout<<::Num<<endl; cout<<Num<<endl; a.a1(); a.a2(); aa::a2(); }
|
转载于:https://blog.csdn.net/zldz14/article/details/81227977