Reputation: 127
everyone.
I have learnt that it is often desirable to write in my codes using std::cout
instead of using namespace std
in order to avoid namespace conflicts. In the following script I only use cout and if I write std:: cout instead of using namespace std; it does not work.
Can anyone please help me understand why? In general, when does std::cout
not work and I am forced to use using namespace std
?
#include <iostream>
#include <string>
using std::cout; //if writing here "using namespace std;" instead, the code does not work
class MyClass{
public:
string name;
MyClass (string n)
{
name=n;
cout<<"Hello "<<name;
}
};
int main()
{
MyClass MyObj("Mike");
return 0;
}
Upvotes: 0
Views: 336
Reputation: 7726
Your code works okay with:
using std::cout;
statement for cout
, but the compiler must know the location of string
(actually it's std::string
) too which you're currently using. You must define:
using std::string;
When you enter:
using namespace std;
It calls the entire namespace called std
which contains a variety of features added as C++ standard library and then you don't need to use prefix std::
for those functions/classes/variables of that namespace.
Upvotes: 1
Reputation: 12954
You need to add using std::string;
along with using std::cout;
to make it work as you're not only using cout from namespace std, string
is also a member of namespace std
which you are using in your code.
Upvotes: 2