类里定义的枚举使用方法

假如有一个类

class Stonewt
{
public:
	enum Format {st, ilb, flb};
private:
	enum {Lbs_per_stn = 14};
	int stone;
	double pds_left;
	double pounds;
	Format fmat;
public:
	Stonewt ( double lbs );
	Stonewt ( int stn, double lbs);
	Stonewt();
	~Stonewt();
	void setFormat(Format form);
	Stonewt operator+ ( const Stonewt & s );
	Stonewt operator- ( const Stonewt & s );
	Stonewt operator* ( double n );
	friend std::ostream & operator<< ( std::ostream & os, const Stonewt & s );
};



友元函数想要用枚举常量,得加作用域符指定哪个类,因为是友元函数,不在类作用域

std::ostream & operator<< ( std::ostream & os, const Stonewt & s )
{
	if ( s.fmat == Stonewt::st )
		os << s.stone << " Stone ," << s.pds_left << " Pounds" << endl;
	if ( s.fmat == Stonewt::ilb )
		os << int ( s.pounds ) << " Pounds(int)" << endl;
	if ( s.fmat == Stonewt::flb )
		os << s.pounds << " Pounds(float)" << endl;
	return os;
}

在main函数里调用得加::

Stonewt a = 275;
Stonewt b ( 285.7 );
Stonewt c ( 21, 8 );

a.setFormat ( Stonewt::st );
b.setFormat ( Stonewt::st );
c.setFormat ( Stonewt::st );



你可能感兴趣的:(C++)