Why is my log in the std namespace?

前端 未结 5 2139
闹比i
闹比i 2020-11-27 15:05

In the code below, I define a trivial log function. In main I try not to call it; I call std::log. Nevertheless, my own

5条回答
  •  独厮守ぢ
    2020-11-27 15:59

    Because you've overridden it in the global namespace. Using a namespace avoids that danger if you don't want to move on to a safer, cleaner language like Nim for example.

    Proper use of namespace demo:

    #include 
    #include   // Uses ::log, which would be the log() here if it were not in a namespace, see http://stackoverflow.com/questions/11892976/why-is-my-log-in-the-std-namespace
    
    // Silently overrides std::log
    //double log(double d) { return 420; }
    
    namespace uniquename {
        using namespace std;  // So we don't have to waste space on std:: when not needed.
    
        double log(double d) {
            return 42;
        }
    
        int main() {
            cout << "Our log: " << log(4.2) << endl;
            cout << "Standard log: " << std::log(4.2);
            return 0;
        }
    }
    
    // Global wrapper for our contained code.
    int main() {
        return uniquename::main();
    }
    

    Output:

    Our log: 42
    Standard log: 1.43508
    

提交回复
热议问题