c++运算符重载
来源:互联网 发布:linux tail f 编辑:程序博客网 时间:2024/06/11 06:32
//问题一: 为什么编译过不了, error LNK2019: 无法解析的外部符号 "class Point __cdecl operator*(int const &,class Point const &)" (<a target=_blank href="mailto:??D@YA?AVPoint@@ABHABV0@@Z">??D@YA?AVPoint@@ABHABV0@@Z</a>),该符号在函数 _main 中被引用// 把第一个友元函数注释掉就可以通过了(主函数要删掉对应的调用)// 答案: 函数的定义参数列表少了一个const//问题二: 如何理解输出流?为什么cout<<a<<++a<<endl; 跟 cout<<a; cout<<++a<<endl; 结果不一样?// 是不是先把cout<<后面的所有表达式计算玩了在一次性输出?//答案 : 还木有#include <iostream>using namespace std;class Point{private:int x, y;public:Point(int x = 0, int y = 0) :x(x), y(y){} //构造函数Point operator++(int); //不能设为常函数,需要改变自身的值,重载后置单目运算符 Point & operator++(); // 重载前置单目运算符Point operator+(const Point &a)const; //后面的const把函数设为常函数,不可以改变自身值(前面加const将把函数返回值设为常量,无法更改值)Point & operator += (const Point &a); //不能设为常函数,需要改变自身的值Point & operator*=(const int &n);Point operator*(const int &n)const; //重载乘法运算符,后面乘以一个数friend Point operator*(const int &n, const Point & a); //n*Point 后面不能接const,n和a都是常量了,不是类成员函数friend int operator *(const Point &a, const Point &b); //坐标点乘friend ostream &operator<<(ostream &out, const Point &c){out << "x = " << c.x << " " << "y = " << c.y << endl;return out;}};int main(){Point a(4, 5);Point b(2, 1);/*cout << a;cout << a++;cout << a;cout << ++a;cout << 4 * a;cout << a * 4;cout<< (a *= 4);cout << endl;cout << a*b << endl;cout << a + b << (a += b);*///两种输出方法结果不一样……cout << a << a++ << a << ++a << 4 * a << a * 4 << (a*=4)<<endl;cout << a*b << endl;cout << a + b << (a+=b);system("PAUSE");return 0;}Point & Point::operator++(){x++;y++;return *this;}Point Point::operator++(int){Point old = *this; //保留旧值this->x++;this->y++;//++(*this); //或者调用前置的return old;}Point Point:: operator+(const Point &a) const // Point + Point{Point b; //创建临时对象,作为返回值b.x = x + a.x;b.y = y + a.y;//x+=a.x; --错!!不能改变自身的值//y+=a.y;//return *this;return b;}Point Point::operator*(const int &n) const //Point * int{Point b(x*n, y*n);return b;}Point operator*(const int &n, const Point & a) // int * Point{Point b(a.x*n, a.y*n);return b;}Point &Point:: operator +=(const Point &a) //Point += Point{this->x += a.x;this->y += a.y;return *this;}Point &Point:: operator*=(const int &n) //Point *= int{ this->x *= n;this->y *= n;return *this;}int operator *(const Point &a, const Point &b) //点乘{return a.x*b.x + a.y*b.y;}
0 0
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- [C++]运算符重载
- 【c++】运算符重载
- C++:运算符重载
- C#:运算符重载
- C++:运算符重载
- 输出1000-2000之间的润年
- 数据库多表链接
- Exercise
- Linux 常用命令速查【长期更新】
- 双向链表--图解
- c++运算符重载
- 矩阵链乘法(动态规划法)
- 黑马程序员——Java概述+环境搭建和变量配置
- uva 607(dp)
- UVa 1594 - Ducci Sequence
- JS定时刷新页面及跳转页面
- uva607(DP)
- QT弹出对话框&文件读取&设置tab键的顺序和光标的位置&lineedit
- android StringBuffer类的使用