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); }; #endifTest.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); }
成員函數是類的一部分,經過對象來調用,能夠直接訪問類成員。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); }; #endifTest.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;}