简体   繁体   中英

Unable to define a global variable in C++

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 .

I'm guessing this is close to the error you get:

In function 'int main()':
Line 13: error: reference to 'count' is ambiguous
compilation terminated due to -Wfatal-errors.

Using the namespace std makes count refer to std::count which is an algorithm in the standard library.

http://www.cplusplus.com/reference/algorithm/count/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM