都说构造函数不返回值。但是下面这个程序是怎么回事?
#include <iostream>
#include <stdlib.h>
using namespace std;
class Candy
{
public:
Candy() {};
Candy( char* color ) { m_color = color; }
char* candy_color() const { return m_color; }
Candy& candy_color( char* color ) { m_color = color; return *this; }
private:
char* m_color;
};
class Child
{
public:
Child( char* name ) { m_name = name; }
void eat( Candy sth ) const;
private:
char* m_name;
};
void Child::eat( Candy sth ) const
{
cout <<
m_name <<
" eat off a " <<
sth.candy_color() <<
" candy." << endl;
}
int main ()
{
Child ch0( "Stan" );
Candy ca0 = Candy( "red" );
Candy ca1;
Candy ca2 = Candy( "white" ).candy_color( "green" );
ca1 = Candy( "yellow" );
ch0.eat( ca0 );
ch0.eat( ca1 );
ch0.eat( ca2 );
ch0.eat( Candy( "blue" ) );
cout << Candy( "black" ).candy_color() << endl;
system( "pause" );
return 0;
} |