无法在C ++中定义全局变量 [英] Unable to define a global variable in C++

查看:168
本文介绍了无法在C ++中定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的新手,并且一直很高兴地通过《 C ++入门指南》 (我非常喜欢!)来工作。但是,我遇到了一个问题。在第5章中,Schildt讨论了全局变量,他提出了一个小程序来演示如何使用它们:

  #include< ; iostream> 
使用命名空间std;

void func1();
void func2();

int计数;

int main()
{
int i;
for(i = 0; i< 10; i ++){
count = i * 2;
func1();
}
cin.get();
返回0;
}

void func1()
{
cout<< count:<<计数; //访问全局计数
cout<< \n;
func2();
}

void func2(){
int count;
for(count = 0; count< 3; count ++)
cout<< 。;
}

编译代码时,每当变量计数在程序的主块和其他功能中使用。这是编译器的问题吗(Visual Studio Express 2013?我是否需要在全局变量前加上一些前缀以便可以使用它?

解决方案

count 在代码和标准库(在std命名空间中)中都定义。 将整个Standard名称空间拖到全局名称空间中会产生歧义,您应该至少执行以下一项操作:




  • 从全局名称空间中删除使用名称空间 std;在函数中使用名称空间,或仅使用所需的名称,或在使用时限定所有标准名称他们
    谨慎选择自己的名称,以避免与标准名称冲突

  • 将名称 count 更改为 * 避免歧义的其他方法。

  • 限定对全局 count 的引用,编写 :::计数




* )特别要注意的是,标准库还定义了名称 distance


I'm new to programming and have been happily working my way through C++ A Beginner's Guide (which I'm thoroughly enjoying!). However, I've come across a bit of an issue. In chapter 5, Schildt talks about global variables and he presents this small program to show how they could be used:

#include <iostream>
using namespace std;

void func1();
void func2();

int count;

int main()
{
    int i;
    for (i = 0; i < 10; i++){
        count = i * 2;
        func1();
    }
    cin.get();
    return 0;
}

void func1()
{
    cout << "count: " << count; // Access global count
    cout << "\n";
    func2();
}

void func2(){
    int count;
    for (count = 0; count < 3; count++)
        cout << ".";
}

When I compile the code, I'm presented with an error message whenever the variable count is used within the main block and other functions of the program. Is this an issue with the compiler (Visual Studio Express 2013? Do I need to prefix the global variable with something so that it can be used?

解决方案

count is defined in both your code and by the Standard Library (in the std namespace). Your use of using namespace std; to drag the entire Standard namespace into the global namespace creates an ambiguity. You should do at least one of the following:

  • remove using namespace std from the global namespace; either use the namespace within your functions, or use just the names you need, or qualify all the standard names when you use them carefully choose your own names to avoid conflicts with standard names
  • change the name count to *something else to avoid ambiguity.
  • qualify the references to the global count, writing ::count.


*) Note in particular that the standard library also defines the name distance.

这篇关于无法在C ++中定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆