65,211
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
using namespace std;
class Item
{
private:
char sex;
int height;
int weight;
public:
Item();
Item& setHeight( int iHeight);
Item& setWeight( int iWeight);
friend ostream& operator << (ostream& c, Item& rhs)
{
c << rhs.sex << "\t" << rhs.height << "\t" << rhs.weight << endl;
return c;
}
};
Item::Item():sex('m'),height(180),weight(100){};
Item& Item::setHeight( int iHeight)
{
this->height = iHeight;
return *this;
}
Item& Item::setWeight( int iWeight)
{
this->weight = iWeight;
return *this;
}
int main()
{
Item i;
cout << i << i;
i.setHeight(300);
i.setWeight(500);
Item j = *new Item();
cout << i << j;
}
/*因为这个函数:
ostream& operator < < (ostream& c, Item& rhs)
{
c < < rhs.sex < < "\t" < < rhs.height < < "\t" < < rhs.weight < < endl;
return c;
}
在类外面调用了类中的私有成员,但此函数既不是成员函数也不是友元函数。*/
#include <iostream>
using namespace std;
class Item
{
private:
char sex;
int height;
int weight;
public:
Item();
Item& setHeight( int iHeight);
Item& setWeight( int iWeight);
friend ostream& operator << (ostream& c, Item& rhs);
};
Item::Item():sex('m'),height(180),weight(100){}
Item& Item::setHeight( int iHeight)
{
this->height = iHeight;
return *this;
}
Item& Item::setWeight( int iWeight)
{
this->weight = iWeight;
return *this;
}
ostream& operator << (ostream& c, Item& rhs)
{
c << rhs.sex << "\t" << rhs.height << "\t" << rhs.weight << endl;
return c;
}
int main()
{
Item i;
cout << i << i;
i.setHeight(300);
i.setWeight(500);
Item j = *new Item();
cout << i << j;
system("pause");
return 0;
}