//"::"双冒号作用域运算符的用法
#include<iostream>
using namespace std;
int count=3;
class A {
public:
static int count; // 类A的count (A::count)
int add(int a,int b);
int add_count(int a,int b);
};
//2 在类定义外扩展定义类内函数
int A::add(int a,int b){
return a+b;
}
//3 在2中,使用类内变量
int A::add_count(int a,int b){
return a+b+A::count;
}
int A::count;
int main(){
//1 区分不同作用域的重名变量,输出3,3,7
A::count=7;
cout<<count<<endl;//不加::默认为全局count
cout<<::count<<endl;
cout<<A::count<<endl;
A B;
B.count=3;
//测试2,输出3
int b=B.add(1,2);
cout<<b<<endl;
//测试3,输出6
int c=B.add_count(1,2);
cout<<c<<endl;
return 0;
}
C++中 :: 双冒号作用域运算符
最新推荐文章于 2026-01-03 02:32:32 发布
本文通过一个具体的示例详细介绍了C++中作用域解析运算符::的使用方法,包括如何区分不同作用域内的重名变量、如何在类内部访问静态成员变量等。并通过几个测试案例展示了这些用法的实际效果。
4021

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



