int * p;
p = 0; // is this right?
if(p == 0) ....
//in this case, the 0 means the address or the null? I am little confused
2.overloading << confusing:
1 2 3 4
ostream & operator<<(ostream & os, className & X) {
os << "... "; // why use os, why dno't use cout?
// why os don't use like std::os, otherwise use std::ostream?
}
string name = "John";
Player * temp = new Player(name); // is this call Player(const sting & name) ?
// why can use like this, I've learned that after "new", it's a type name or type name and a value within a parameters
// I use new before just for dynamic memory, what's this usage?
1) No. Use NULL or better nullptr (if your compiler supports C++11).
Also, instead of
1 2
int * p;
p = 0; // is this right?
int * p = nullptr;
is better practice
2) You can use cout but the purpose of overloading insertion operator is to be able to be able to correctly insert data into the ostream or streams derived from it and enable cascading.
Something like
1 2 3 4 5 6 7
Player one;
Player two;
cout << one << two;
fstream off("some file");
off << one;
So if you do a cout inside it will always print on the console.
3) Yes its calling the constructor of the class Player
this syntax of new is calling the constructor of class player
1 2 3 4 5 6 7
Player *one = nullptr;
...
one = new Player("some"); //calling constructor of player
Player *arr = new Player[10]; //Allocating space for 1o player objects or in other words creating array of Player
#include <iostream>
class Test
{
public:
Test ( std::string name) :
n ( name ){}
std::string get_name () { return n ; }
private:
std::string n ;
};
std::ostream & operator<< ( std::ostream & os, Test t)
{
os << t.get_name () ;
return os ;
}
int main ( int argc, char ** argv )
{
Test * t = 0 ;
if( t )
std::cout << *t << std::endl;
else
std::cout << "there is no test"
<< std::endl;
if ( !t )
t = new Test ( "my name is test" ) ;
else
std::cout << "test already has an address"
<< std::endl;
if( t )
std::cout << *t << std::endl;
else
std::cout << "there is no test"
<< std::endl;
if ( !t )
t = new Test ( "my name is test" ) ;
else
std::cout << "test already has an address"
<< std::endl;
delete t ;
t = 0 ;
if( t )
std::cout << *t << std::endl;
else
std::cout << "there is no test"
<< std::endl;
return 0;
}
The problem is that std::cout is a class derived from std::ostream.
The coutobject is a very specific ostream object. It generally writes to the console. But ostream objects can be used to write to a string, write to a file, write to an error stream, etc. If we put cout into the operator<<function, we would only write to the console.
cout <<
means "write some data to the specific standard output stream for my system" (usually the console). On the other hand, os <<
means "write some data to the stream that I will tell you about".