Each "include" line causes the compiler to read whatever is in the file specified at each include, as if it were written in that file.
The namespace line declares that the code assumes all members of namespace std should be assumed. Namespaces enclose declarations. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
namespace nsA
{
void function();
}
namespace nsB
{
void function();
}
int main()
{
function(); // this is ambiguous, and is an error
nsA::function(); // the compiler accepts this, calls nsA's version of function, not nsB's.
return 0;
}
|
The first call to function is an error. The compiler will not recognize EITHER function with just that call.
The second call to function is valid, because the explicitly references namespace nsA. It could also have called nsB::function to call the other version.
If I had included a line before main, using namespace nsB, that would have made the first call valid. The compiler would have assumed you intend to use namespace nsB, and would therefore have realized what you meant in the first call to function.
You would cause confusing of you issued both:
1 2 3 4
|
using namespace nsA;
using namespace nsB;
|
If both of were written, the first call to function is ambiguous, the compiler can't figure out which one you really mean.
This is why the using namespace feature of C++ is cautionary. It's especially important not to write this declaration in a header file. Only in CPP files, and only when you know it won't cause the kind of confusion just illustrated.
The standard C++ library is in namespace std. As such, the using namespace std; is a typical call to make it convenient to use standard library classes and functions. Without it, you've to explicate the namespace for all standard library objects and functions (i.e. std::cout instead of just cout).
1 2 3 4 5 6
|
string operator*(const string& s, unsigned int n) {
stringstream out;
while (n--)
out << s;
return out.str();
}
|
This declares an operator function, overloading the '*' operator. It is not written to do what is expected of it, because * should either perform a multiplication, or dereference a pointer.
I'll skip the body of the function itself because it doesn't make sense in the context of a * operator...it appears to be there simply to show the function was called.
There is a second overload of the * operator taking the parameters in reverse. This is intended to allow the multiplication of a string by an integer, or an integer multiplied by a string.
That's not actually a good idea, but that's what it's determined to try to do. Multiplying "cat" by 5 would be a strange result...might be "catcatcatcatcat" or 45, it the function realized cat's have 9 lives.
int main....that's the main function. If you don't know what that is, start with a "hello world" example.
system("pause"); is a "quick 'n' dirty" way to make the thing wait before exiting.