1、operator long ()
成员转换函数把类的对象转换为其他数据类型的对象。
在表达式的内部,如果某个类型和需要的类型不一致,就会发生转换。
1 #include <iostream>
2
3 class Date
4 {
5 int mo, da, yr;
6
7 public:
8 Date(int m, int d, int y) { mo = m; da = d; yr = y; }
9 operator long(); // member conversion function.
10 };
11
12 Date::operator long()
13 {
14 static int dys[]={31,28,31,30,31,30,31,31,30,31,30,31};
15 long days = yr - 1900;
16 days *= 365;
17 days += yr / 4;
18 for (int i = 0; i < mo-1; i++)
19 days += dys[i];
20 days += da;
21
22 return days;
23 }
24
25 int main()
26 {
27 Date xmas(12, 25, 1997);
28 long since = xmas;
29 std::cout << since << std::endl;
30
31 Date today(2, 12, 1990);
32 const long ott = 123;
33 long sum = ott + today; // today is converted to long.
34 std::cout << ott << " + " << (long) today << " = " << sum;
35
36 return 0;
37 }
2、operator CustomDate()
对类进行转换
调用转换函数三种方法:一是隐式转换,二是强制类型转换,三是显示调用转换构造函数和成员转换函数。分别为程序的64、68、72行
1 #include <iostream>
2
3 class CustomDate
4 {
5 public:
6 int da, yr;
7 CustomDate(int d = 0, int y = 0) { da = d; yr = y;}
8 void display(){ std::cout << std::endl
9 << yr << '-' << da; }
10 };
11
12 class Date
13 {
14 int mo, da, yr;
15
16 public:
17 // Constructor.
18 Date(int m = 0, int d = 0, int y = 0)
19 { mo = m; da = d; yr = y; }
20
21 // Constructor conversion function.
22 Date(const CustomDate&);
23
24 // Member conversion function.
25 operator CustomDate();
26
27 void display(){std::cout << std::endl
28 << mo << '/' << da
29 << '/' << yr;}
30 };
31
32 static int dys[] = {31,28,31,30,31,30,31,31,30,31,30,31};
33
34 // Constructor conversion function (Date <- CustomDate).
35 Date::Date(const CustomDate& jd)
36 {
37 yr = jd.yr;
38 da = jd.da;
39 for (mo = 0; mo < 11; mo++)
40 if (da > dys[mo])
41 da -= dys[mo];
42 else
43 break;
44 mo++;
45 }
46
47 // Member conversion function (CustomDate <- Date)
48 Date::operator CustomDate()
49 {
50 CustomDate cd(0, yr);
51 for (int i = 0; i < mo-1; i++)
52 cd.da += dys[i];
53 cd.da += da;
54
55 return cd;
56 }
57
58 int main()
59 {
60 Date dt(11,17,97);
61 CustomDate cd;
62
63 // Convert Date to CustomDate. Convert Date to CustomDate via implicit conversion.
64 cd = dt;
65 cd.display();
66
67 // Convert Date to CustomDate via cast.
68 cd = (CustomDate) dt;
69 cd.display();
70
71 // Convert Date to CustomDate via constructor
72 cd = CustomDate(dt);
73 cd.display();
74
75 // Convert CustomDate to Date
76 dt = cd;
77 dt.display();
78
79 return 0;
80 }
3、重载赋值运算符函数(Date& operator=(const Date&);)
#include <iostream>
#include <cstring>
class Date
{
int mo, da, yr;
char *month;
public:
Date(int m = 0, int d = 0, int y = 0);
~Date();
// Overloaded assignment operator.
Date& operator=(const Date&);
void display() const;
};
// The constructor definition.
Date::Date(int m, int d, int y)
{
static char *mos[] =
{
"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December"
};
mo = m; da = d; yr = y;
if (m != 0)
{
month = new char[strlen(mos[m-1])+1];
strcpy(month, mos[m-1]);
}
else
month = 0;
}
// The destructor definition.
Date::~Date()
{
delete [] month;
}
// Display member function.
void Date::display() const
{
if (month != 0)
std::cout << month << ' ' << da
<< ", " << yr << std::endl;
}
// Overloaded Date assignment.
Date& Date::operator=(const Date& dt)
{
if (this != &dt)
{
mo = dt.mo;
da = dt.da;
yr = dt.yr;
delete [] month;
if (dt.month != 0)
{
month = new char [strlen(dt.month)+1];
strcpy(month, dt.month);
}
else
month = 0;
}
return *this;
}
int main()
{
// Original date.
Date birthday(6,24,40);
Date oldday, newday;
// Assign first to second to third.
oldday = newday = birthday;
birthday.display();
oldday.display();
newday.display();
return 0;
}
if (this != &dt)是为了防止同时对一个指针进行两次删除操作4、在类内部重载new和delete运算符
void* operator new(size_t) throw(std::bad_alloc)
void operator delete(void* p) throw() 可以重载全局new和delete运算符,但一般不这么做。不过采用重载可以获得较高的效率,避免使用全局new和delete运算符带来的额外开销。
#include <iostream>
#include <cstring>
#include <cstddef>
#include <new>
const int maxnames = 5;
class Names
{
char name[25];
static char Names::pool[];
static bool Names::inuse[maxnames];
public:
Names(char* s)
{ strncpy(name, s, sizeof(name)); }
void* operator new(size_t) throw(std::bad_alloc);
void operator delete(void*) throw();
void display() const
{ std::cout << name << std::endl; }
};
// Simple memory pool to handle fixed number of Names.
char Names::pool[maxnames * sizeof(Names)];
bool Names::inuse[maxnames];
// Overloaded new operator for the Names class.
void* Names::operator new(size_t) throw(std::bad_alloc)
{
for (int p = 0; p < maxnames; p++)
{
if (!inuse[p])
{
inuse[p] = true;
return pool+p*sizeof(Names);
}
}
throw std::bad_alloc();
}
// Overloaded delete operator for the Names class.
void Names::operator delete(void* p) throw()
{
if (p != 0)
inuse[((char*)p - pool) / sizeof(Names)] = false;
}
int main()
{
Names* nm[maxnames];
int i;
for (i = 0; i < maxnames; i++)
{
std::cout << std::endl << "Enter name # "
<< i+1 << ": ";
char name[25];
std::cin >> name;
nm[i] = new Names(name);
}
for (i = 0; i < maxnames; i++)
{
nm[i]->display();
delete nm[i];
}
return 0;
}
5、重载new[]和delete[]运算符
#include <iostream>
#include <cstring>
#include <cstddef>
#include <new>
const int maxnames = 5;
class Names
{
char name[25];
static char Names::pool[];
static short int Names::inuse[maxnames];
public:
Names(char* s = 0)
{
if (s)
strncpy(name, s, sizeof(name));
}
void* operator new[](size_t) throw(std::bad_alloc);
void operator delete[](void*) throw();
void display() const
{ std::cout << name << std::endl; }
};
// Simple memory pool to handle fixed number of Names.
char Names::pool[maxnames * sizeof(Names)];
short int Names::inuse[maxnames];
// Overloaded new[] operator for the Names class.
void* Names::operator new[](size_t size) throw(std::bad_alloc)
{
int elements = size / sizeof(Names);
// Find the first empty element (if any).
int p = -1;
int i = 0;
while ((i < maxnames) && (p == -1))
{
if (!inuse[i])
p = i;
++i;
}
// Not enough room.
if ((p == -1) || ((maxnames - p) < elements))
throw std::bad_alloc();
// Mark the elements as used.
for (int x=0; x<elements; ++x)
inuse[p+x] = elements;
// Return pointer to memory.
return pool+p*sizeof(Names);
}
// Overloaded delete[] operator for the Names class.
void Names::operator delete[](void* b) throw()
{
if (b != 0)
{
int p = ((char*)b - pool) / sizeof(Names);
int elements = inuse[p];
for (int i = 0; i < elements; i++)
inuse[p + i] = 0;
}
}
int main()
{
Names* np = new Names[maxnames];
int i;
for (i = 0; i < maxnames; i++)
{
std::cout << std::endl << "Enter name # "
<< i+1 << ": ";
char name[25];
std::cin >> name;
*(np + i) = name;
}
for (i = 0; i < maxnames; i++)
(np + i)->display();
delete [] np;
return 0;
}
6、重载+运算符
这里分别用了成员函数和非成员函数对“+”符号进行了重载
Date Date::operator+(int) const
Date operator+(int n, Date& dt)
#include <iostream>
class Date
{
int mo, da, yr;
static int dys[];
public:
Date(int m=0, int d=0, int y=0)
{ mo = m; da = d; yr = y; }
void display() const
{ std::cout << mo << '/' << da << '/' << yr; }
// Overloaded + operator.
Date operator+(int) const;
};
int Date::dys[]={31,28,31,30,31,30,31,31,30,31,30,31};
// Overloaded + operator: Date + int.
Date Date::operator+(int n) const
{
Date dt = *this;
n += dt.da;
while (n > dys[dt.mo-1])
{
n -= dys[dt.mo-1];
if (++dt.mo == 13)
{
dt.mo = 1;
dt.yr++;
}
}
dt.da = n;
return dt;
}
Date operator+(int n, Date& dt)
{
return dt + n;
}
int main()
{
Date olddate(2,20,1997);
Date newdate;
newdate = 11 + olddate + 10; // three weeks hence
newdate.display();
return 0;
}
7、重载关系运算符(“==”“< ”“+=”)
Date operator+=(int n)
int operator==(Date& dt) const
int operator<(Date&) const
#include <iostream>
class Date
{
int mo, da, yr;
public:
Date(int m=0, int d=0, int y=0)
{ mo = m; da = d; yr = y; }
void display() const
{ std::cout << mo << '/' << da << '/' << yr; }
// Overloaded + operator.
Date operator+(int) const;
// Overloaded += operator.
Date operator+=(int n)
{ *this = *this + n; return *this; }
// Overloaded operators.
int operator==(Date& dt) const;
int operator<(Date&) const;
};
int dys[]={31,28,31,30,31,30,31,31,30,31,30,31};
// Overloaded + operator definition.
Date Date::operator+(int n) const
{
Date dt = *this;
n += dt.da;
while (n > dys[dt.mo-1])
{
n -= dys[dt.mo-1];
if (++dt.mo == 13)
{
dt.mo = 1;
dt.yr++;
}
}
dt.da = n;
return dt;
}
// Overloaded equality operator definition.
int Date::operator==(Date& dt) const
{
return (this->mo == dt.mo &&
this->da == dt.da &&
this->yr == dt.yr);
}
// Overloaded less-than operator definition.
int Date::operator<(Date& dt) const
{
if (this->yr == dt.yr) {
if (this->mo == dt.mo)
return this->da < dt.da;
return this->mo < dt.mo;
}
return this->yr < dt.yr;
}
int main()
{
Date date1(12,7,1941),
date2(2,22,1990),
date3(12,7,1941);
Date olddate(2,20,1997);
olddate += 21; // three weeks hence
olddate.display();
std::cout<<std::endl;
if (date1 < date2)
{
date1.display();
std::cout << " is less than ";
date2.display();
}
std::cout << '\n';
if (date1 == date3)
{
date1.display();
std::cout << " is equal to ";
date3.display();
}
return 0;
}
8、重载自增运算符(++)
Date operator++():重载++i
Date operator++(int):重载i++
#include <iostream>
class Date
{
int mo, da, yr;
static int dys[];
public:
Date(int m=0, int d=0, int y=0)
{ mo = m; da = d; yr = y; }
void display() const
{ std::cout << '\n' << mo << '/' << da << '/' << yr;}
// Overloaded + operator.
Date operator+(int) const;
// Overloaded prefix ++ operator.
Date operator++()
{ *this = *this + 1; return *this; }
// Overloaded postfix ++ operator.
Date operator++(int)
{ Date dt=*this; *this=*this+1; return dt; }
};
int Date::dys[]={31,28,31,30,31,30,31,31,30,31,30,31};
// Overloaded + operator definition.
Date Date::operator+(int n) const
{
Date dt = *this;
n += dt.da;
while (n > dys[dt.mo-1])
{
n -= dys[dt.mo-1];
if (++dt.mo == 13)
{
dt.mo = 1;
dt.yr++;
}
}
dt.da = n;
return dt;
}
int main()
{
Date olddate(2,20,1997);
olddate++;
olddate.display();
++olddate;
olddate.display();
return 0;
}
9、重载单目负运算符(-i)
int operator-() const
#include <iostream>
#include <cstring>
class ItemQty
{
int onhand;
char desc[25];
public:
ItemQty(int oh, char *d)
{ onhand = oh; strcpy(desc, d); }
void display() const
{ std::cout << '\n' << desc <<"huhu"<<strlen(desc)<< ": " << onhand; }
// Overloaded unary - operator.
int operator-() const
{ return -onhand; }
};
int main()
{
ItemQty item1(100, "crankshaft");
ItemQty item2(-50, "driveshaft");
item1.display();
std::cout << '\n' << -item1; // invoke the overloaded -
item2.display();
std::cout << '\n' << -item2; // invoke the overloaded -
return 0;
}
10、重载下标运算符([])
char& operator[](int n)
const char& operator[](int n) const
只有当所有的String类对象都是非常量的时候,才能用第一个重载[]运算符函数来得到字符串中的字符。为了支持常量String对象类中还设计了第二个重载[]运算符。
#include <iostream>
#include <cstring>
class String
{
char* sptr;
public:
String(char* s = 0);
~String() { delete sptr; }
void display()
{ std::cout << sptr << std::endl; }
// Overloaded [] operator.
char& operator[](int n)
{ return *(sptr + n); }
const char& operator[](int n) const
{ return *(sptr + n); }
};
// The String class constructor.
String::String(char* s)
{
if (s)
{
sptr = new char[strlen(s)+1];
strcpy(sptr, s);
}
else
sptr = 0;
}
int main()
{
String string1("The Ides of March");
string1.display();
// Change some string characters.
string1[4] = '1';
string1[5] = '5';
string1[6] = 't';
string1[7] = 'h';
string1.display();
// Change a substring.
strncpy(&string1[4], "21st", 4);
string1.display();
// const string, cannot be modified.
const String string2("Et tu, Brute?");
for (int i = 0; i < 13; i++)
std::cout << string2[i];
return 0;
}
11、成员指针运算符(—>)
Date* operator->()
为了防止由于疏忽,没有把一个有效地Date对象的地址复制给指针,而使指针指向了无意义的地方,会导致程序崩溃。
DatePtr对象是一个指针,它知道自身是否已经被赋值。即使没有任何Date类对象的地址赋给指针,指针不会指向一个空的Date对象。
#include <iostream>
class Date
{
int mo, da, yr;
public:
Date(int m=0, int d=0, int y=0)
{ mo = m; da = d; yr = y; }
void display()
{ std::cout << '\n' << mo << '/' << da << '/' << yr; }
};
class DatePtr
{
Date* dp;
public:
DatePtr(Date* d = 0) { dp = d; }
Date* operator->()
{
static Date nulldate(0,0,0);
if (dp == 0) // if the pointer is null
return &nulldate; // return the dummy address
return dp; // otherwise return the pointer
}
};
int main()
{
// Date pointer with nothing in it.
DatePtr dp;
// Use it to call display function.
dp->display();
Date dt(3,17,90);
// Put address of date in pointer.
dp = &dt;
// Display date through the pointer.
dp->display();
return 0;
}
posted on 2009-06-22 20:31
The_Moment 阅读(984)
评论(0) 编辑 收藏 引用 所属分类:
C\C++