<C++>1.作用域标识符

本文探讨了C++编程语言中全局变量与局部变量共名时的作用域问题,并介绍了如何通过作用域标识符来区分并使用它们。

一般情况下,若有两个同名的变量,其中一个是全局变量,另一个是局部变量,那么局部变量在其作用域内具有优先权。

例:

#include <iostream>
using namespace std;

int a=1;
int main(void)
{
	int a=2;
	cout<<::a<<endl;
	
	return 0;
}

输出的值为a=2。

我们若想使用全局变量a,则应加作用域标识符:

cout<<::a<<endl;
这样输出的a值就为1了。

同样,在main函数里更改全局变量a的值也得使用作用域标识符:

#include <iostream>
using namespace std;

int a=1;
int main(void)
{
	int a=2;
	::a=3;
	cout<<::a<<endl;
	
	return 0;
}




#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> using namespace std; // 统计单词数量函数 int countWords(ifstream& file) { int count = 0; string word; while (file >> word) { // 自动过滤空白字符 count++; } return count; } // 统计特定字符串出现次数函数 int countOccurrences(const string& text, const string& target) { int count = 0; size_t pos = 0; while ((pos = text.find(target, pos)) !=string::npos) { count++; pos += target.length(); } return count; } int main() { //打开并读取文件 ifstream file("Chapter5InJourneyToWest.txt"); if (!file.is_open()) { cout << "错误:无法打开文件" << endl; return 1; } //统计总字数 int totalWords = countWords(file); // 重置文件指针读取完整内容 file.clear(); file.seekg(0); string content((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); file.close(); // 3. 统计人物出现次数 vector<pair<string, int>> characters = { {"大王", countOccurrences(content, "大王")}, {"玉帝", countOccurrences(content, "玉帝")}, {"七仙女", countOccurrences(content, "七仙女")}, {"大圣", countOccurrences(content, "大圣")} }; // 按出现次数排序 sort(characters.begin(), characters.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); // 输出结果 cout << "总字数: " << totalWords << endl; cout << "人物分析:" <<endl; for (const auto& [name, count] : characters) { cout << name << ": " << count << " 次\n"; } // 选择关键角色(取前两名) cout << "关键角色:" << endl; cout<< "1. " << characters[0].first << endl; cout<< "2. " << characters[1].first << endl; return 0; } 现在这个程序报错,未定义标识符 “name”,你来修改
03-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值