1.
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.
成员函数是类的一部分,通过对象来调用,可以直接访问类成员。
友元函数不是类的一部分,直接调用,要通过成员运算符来访问成员,不过可以访问私有成员。
3.
如果是私有成员,必须是友元,如果是共有的,就没关系。
4.
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);
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.
sizeof
.
::
?:
.*
6.
重载=,[],(),->必须是成员函数
7.
operator double() { return mag;}