面向对象程序设计-C++ Default constructor & Copy constructor& Destructor & Operator Overloading【第九次上课笔记】
先上笔记内容吧:
这次上课的内容有关
- 构造函数
- 析构函数
- 运算符重载
- return * this
内容很细,大家好好回顾笔记再照应程序复习吧 :)
#include <iostream> using namespace std; class Integer { public: int i; int geti () const {return this->i;} void seti (int i) {this->i = i;} Integer(int j = 0); Integer(Integer & c); ~Integer(); }; Integer::Integer (Integer & c) { //Constructer Function i = 18; cout << "Integer (Integer & c)" << endl; } Integer::Integer (int j) : i(j) { //Copy Constructer Function cout << "Integer (int j)" << endl; } Integer::~Integer () { //Destructer Function cout << "~Integer () " << endl; } const Integer & fun (const Integer & in) { cout << in.geti () << endl; return in; } int main (){ Integer b(8); fun(b).geti(); Integer a(b); return 0; }
下面这个程序是有关运算符重载
通过 log print 可以跟踪观察到析构的顺序
同时还有引用返回、友元函数的例子
#include <iostream> using namespace std; class Integer { private: int i; public: int geti () const {return this->i;} void seti (int i) {this->i = i;} Integer(int j = 0); Integer(Integer & c); ~Integer(); const Integer & operator = (const Integer & in); friend const Integer operator + (const Integer & lhs, const Integer & rhs); }; const Integer & Integer::operator = (const Integer & in) { //Member Function i = in.i + 50; //return in; return *this; } const Integer operator + (const Integer & lhs, const Integer & rhs) { //全局函数 Integer out; out.i = lhs.i + rhs.i; return out; } Integer::Integer (Integer & c) { //Constructer Function i = 18; cout << "Integer (Integer & c)" << endl; } Integer::Integer (int j) : i(j) { //Copy Constructer Function cout << "Integer (int j)" << ‘ ‘ << j << endl; } Integer::~Integer () { //Destructer Function cout << "~Integer () " << ‘ ‘ << i << endl; } int main (){ Integer b(8), a, c, d; cout << "a.geti()" << a.geti() << endl; d = c = a = b; cout << "a.geti()" << a.geti() << endl; cout << "c.geti()" << c.geti() << endl; cout << "d.geti()" << d.geti() << endl; d = a + b; cout << "d.geti()" << d.geti() << endl; return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。