C++中使用类(重载,友元函数,转换函数等)
12点半了。好久没更新C++博文了。把一个章节看完了。接下来说下C++里的操作符重载和以后的内容。时间晚了,可能打字没打好。望大家见谅。
C++中有个operator操作符概念。如果想重载+运算符,那么需要写成operator+()。一般两个数相加是这么调用的:
#include <iostream>using std::cout;#include "stonewt.h"void display(const Stonewt st, int n);int main(){Stonewt pavarotti = 260;//调用构造函数,因为260能转化为浮点型Stonewt wolfe(285.7);//类似Stonewt wolfe = 285.7;Stonewt taft(21,8);cout << "The tenor weighted ";pavarotti.show_stn();cout << "THe detective weighted ";wolfe.show_stn();cout << "The President weighed ";taft.show_lbs();pavarotti = 256.8;//构造函数进行初始化taft = 325;//和 taft = Stonewt(325);一样cout << "After dinner, the tenor weighed ";pavarotti.show_stn();cout << "After dinner, the president weighed ";taft.show_lbs();display(taft, 2);cout << "The wrestler weighted even more.\n";display(422, 2);//将422转化乘 Stonewt对象cout << "No stone left unearned\n";// 使用转换函数将类对象转化为基本类型Stonewt poppins(9, 28);double p_wt = poppins;cout << "COnvert to double => ";cout << "Poppins: " << p_wt << " pounds.\n";cout << "Convert to int => ";cout << "Poppins: " << int(poppins) << " pounds.\n";return 0;}void display(const Stonewt st, int n){for (int i = 0; i < n; i++){cout << "Wow! ";st.show_stn();}}