jianghubazhu 2014-12-26 11:08 采纳率: 0%
浏览 1744

我的运算符重载语法对了但是编译通不过

//问题一: 为什么编译过不了, error LNK2019: 无法解析的外部符号 "class Point __cdecl operator*(int const &,class Point const &)" (??D@YA?AVPoint@@ABHABV0@@Z),
// 该符号在函数 _main 中被引用
// 把第一个友元函数注释掉就可以通过了(主函数要删掉对应的调用)
//问题二: 如何理解输出流?为什么cout<<a<<++a<<endl; 跟 cout<<a; cout<<++a<<endl; 结果不一样?
// 是不是先把cout<<后面的所有表达式计算玩了在一次性输出?

#include

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 << a++ << ++a << 4 * a << a * 4 <<( a *= 4);
cout << endl;
cout << a*b << 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 b;
}

Point Point::operator*(const int &n) const //Point * int
{
Point b;
b.x = x*n;
b.y = y*n;
//this->x*=n; --错!不能改变自身的值
//this->y*=n;
return b;
}

Point operator*(const int &n, Point & a) // int * Point
{
return a*n;
}

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;
}

  • 写回答

3条回答 默认 最新

  • jianghubazhu 2014-12-26 11:12
    关注

    第一次提问,没有处理好代码片……原谅我吧

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口