《C++ Primer Plus(第六版)》(19)(第十一章 使用类 复习题答案)

1.ios

Test.h函数

#ifndef _Test_H_  
#define _Test_H_  

 
class Stonewt
{
private:
	enum {Lbs_per_stn = 14};
	int stone;
	double pds_left;
	double pounds;
public:
	Stonewt(double lbs);
	Stonewt(int stn, double lbs);
	Stonewt();
	~Stonewt();
	void show_lbs() const;
	void show_stn() const;
	operator int() const;
	operator double() const;
	Stonewt operator*(double times);
};


#endif  
Test.cpp

#include "Test.h"  
#include <iostream>  

using namespace std;
 
Stonewt::Stonewt(double lbs)
{
	stone = int(lbs) / Lbs_per_stn;
	pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
	pounds = lbs;
}

Stonewt::Stonewt(int stn, double lbs)
{
	stone = stn;
	pds_left = lbs;
	pounds = stn * Lbs_per_stn + lbs;
}

Stonewt::Stonewt()
{
	stone = pounds = pds_left = 0;
}

Stonewt::~Stonewt()
{

}

void Stonewt::show_lbs() const
{
	cout << pounds << " pounds\n";
}

void Stonewt::show_stn() const
{
	cout << stone << " stone, " << pds_left << " pounds\n";
}

Stonewt::operator int() const
{
	return int(pounds + 0.5);
}

Stonewt::operator double()const
{
	return pounds;
}

Stonewt Stonewt::operator*(double times)
{
	return Stonewt(pounds * times);
}


2.

成员函数是类的一部分,经过对象来调用,能够直接访问类成员。spa

友元函数不是类的一部分,直接调用,要经过成员运算符来访问成员,不过能够访问私有成员。code


3.对象

若是是私有成员,必须是友元,若是是共有的,就不要紧。blog


4.ip

Test.hio

#ifndef _Test_H_  
#define _Test_H_  

 
class Stonewt
{
private:
	enum {Lbs_per_stn = 14};
	int stone;
	double pds_left;
	double pounds;
public:
	Stonewt(double lbs);
	Stonewt(int stn, double lbs);
	Stonewt();
	~Stonewt();
	void show_lbs() const;
	void show_stn() const;
	operator int() const;
	operator double() const;
	Stonewt operator*(double times);
	friend Stonewt operator*(double times, const Stonewt& a);
};


#endif  
Test.cpp

#include "Test.h"  
#include <iostream>  

using namespace std;
 
Stonewt::Stonewt(double lbs)
{
	stone = int(lbs) / Lbs_per_stn;
	pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
	pounds = lbs;
}

Stonewt::Stonewt(int stn, double lbs)
{
	stone = stn;
	pds_left = lbs;
	pounds = stn * Lbs_per_stn + lbs;
}

Stonewt::Stonewt()
{
	pounds = pds_left = stone = 0;
}

Stonewt::~Stonewt()
{

}

void Stonewt::show_lbs() const
{
	cout << pounds << " pounds\n";
}

void Stonewt::show_stn() const
{
	cout << stone << " stone, " << pds_left << " pounds\n";
}

Stonewt::operator int() const
{
	return int(pounds + 0.5);
}

Stonewt::operator double()const
{
	return pounds;
}

Stonewt Stonewt::operator*(double times)
{
	return Stonewt(pounds * times);
}

Stonewt operator*(double times, const Stonewt& a)
{
	return Stonewt(a.pounds * times);
}
这个东西加太多,使用int的话会有二义性。


5.class

sizeofstream

.

::

?:

.*


6.

重载=,[],(),->必须是成员函数


7.

operator double() { return mag;}
相关文章
相关标签/搜索