简体   繁体   中英

overloading << and using namespace std

I need a help with understanding the following:

I overloaded << operator. I wrote a test program. I didnt include the "using namespace std" code. But the program worked out well.

#include <iostream>
#include "fraction.h"

//using namespace std;

int main(void)
{
//constructing two fractions
    Fraction a(4, 2);
    Fraction b(17, 11);
//modifying them that is entering a fractions from keyboard
    cin>>a;
    cin>>b;
//computing product and quotient and printing them using cout
    cout<<a*b<<endl;
    cout<<a/b<<endl;
}

But as you can see I used "endl" which is from standard namespace. Can you explain me the "paradox" I m getting here.

PS I didnt include .h and .cpp file because I think they are irrelevant.

A compiler works with translation unit. It takes a .cpp and then insert .h text inside the translation unit. If your header file includes using namespace std; , it will effectively be present in the code the compiler tries to compile.

This is a bad practice as your are shoving namespace using down your user throat and can induce name clashes if other namespace use the same name.

If you can use cin and cout , and the problem is using endl , then your fraction.h file is most likely including those dependencies either in one of two ways

using std::cin;
using std::cout;
using std::endl;

or

using namespace std;

When you #include something, is does a straight text replacement with the file. Since you #include "fraction.h" and it probably has the line

using namespace std;

the main file also uses std .

Also note, it is not good practice to using namespace std; in header files since everywhere else that includes the header will also automatically use std which can cause conflicts if the programmer is unaware.

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