21xrx.com
2024-04-26 03:23:15 Friday
登录
文章检索 我的文章 写文章
C++ 中的作用域解析运算符
2021-07-08 15:44:24 深夜i     --     --
C + +

C++ 中的作用域解析运算符 (::) 用于在类外定义函数,或者当我们想要使用全局变量但又具有同名的局部变量时。

C++编程代码

#include <iostream>


using namespace std;
 
char c = 'a';     // global variable (accessible to all functions)
 
int main() {
  char c = 'b';   // local variable (accessible only in main function)
 
  cout << "Local  variable: " << c << "\n";      
  cout << "Global variable: " << ::c << "\n";  // Using scope resolution operator
 
  return 0;
}

 

程序输出:

类中的范围解析运算符

#include <iostream>
using namespace std;


class Game {
public:
  void play();  // Function declaration
};

// function definition outside the class

void Game::play() {
  cout << "Function defined outside the class.\n";
}

int main() {
  Game g;
  g.play();

  return 0;
}

 

程序输出:

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复