前言
这篇博客可能会比较短,但是这应该是我研究最久的博客之一了。
思考起因
首先看到这道题,因为位数明显会很大,所以第一个要想到的就是这道题要用到高精。
当然,用到高精度的题很多。
而这道题还要用到快速幂。
同时用到高精和快速幂的题目也很多。
的确。
众所周知,在快速幂运算中,要多次用到乘法。所以乘法的简洁性很重要,否则,程序写起来会很麻烦。而我们只想写这样的快速幂:
1 2 3 4 5 6 7 8 9 10 11 12
| int poww(int a, int b) { int ans = 1, base = a; while (b != 0) { if (b & 1 != 0) ans *= base; base *= base; b >>= 1; } return ans; }
|
以后更难的题中,我们还要用到更多高精乘法。
那怎么办呢?
这就用到我们的运算符重载了。
研究历程
再讲讲我的研究历程吧。
先是想到要用重载运算符,觉得应该和重载函数是一样的,就自己先写了这个:
1 2 3 4
| string operator*(string a,string b) { }
|
发现不太行。
于是从网上找资料:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <iostream> using namespace std; class Box { public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } private: double length; double breadth; double height; };
int main( ) { Box Box1; Box Box2; Box Box3; double volume = 0.0; Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; Box3 = Box1 + Box2; volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include<iostream> using namespace std; class complex { public: complex(double r = 0.0, double i = 0.0) { real = r; imag = i; } const complex operator+(const complex &c) const ; const complex operator - (const complex &c) const; void display(); private: double real; double imag; }; const complex complex:: operator+(const complex &c) const { return complex(real + c.real, imag + c.imag); } const complex complex:: operator-(const complex &c) const { return complex(real - c.real, imag - c.imag); } void complex::display() { cout << "(" << real << "," << imag << " i)" << endl; } void main() { complex c1(5, 4), c2(2, 10), c3; cout << "c1="; c1.display(); cout << "c2="; c2.display(); c3 = c1 + c2; cout << "c3=c1+c2="; c3.display(); c3 = c1 - c2; cout << "c3=c1-c2="; c3.display(); }
|
全都是这种。
这些东西,让我这个连类都不知道是什么的蒟蒻怎么看得懂?!
继续不停的翻找,还都是这些。
突然,灵光一现
以前我在上清北学堂的时候,老师讲过大于、小于号的重载!
于是又返回去看:
终于找到了!就是这个!
正文
这只是一个记录学习历程的博客,所以正文很短。
所以我们要写的重载高精度乘法就是这样:
1 2 3 4 5
| string operator*(const string &a,const string &b) { return ; }
|
还有这个:
