为了账号安全,请及时绑定邮箱和手机立即绑定

error C2593: 'operator -' is ambiguous

头文件:

class Coordinate

{

friend Coordinate &operator-(Coordinate &c);

public: 

Coordinate();

Coordinate(int x,int y);

Coordinate &operator-();

~Coordinate();

int getX();

void setX(int x);

int getY();

void setY(int y);

private:

int m_iX;

int m_iY;

 };

实现类:

#include "Coordinate.h"

#include <iostream>


using namespace std;

Coordinate::Coordinate(int x,int y){

m_iX = x;

m_iY = y;

cout<<"Coordinate() "<<m_iX<<","<<m_iY<<endl;

};

//Coordinate &Coordinate::operator-(){

// this->m_iX=-this->m_iX;

// this->m_iY=-this->m_iY;

// return *this;

// };

Coordinate &operator-(Coordinate &c){

c.m_iX = -c.m_iX;

c.m_iY = -c.m_iY;

return c;

};

Coordinate::Coordinate(){

cout<<"Coordinate() "<<endl;

};


Coordinate::~Coordinate(){

cout<<"~Coordinate() "<<m_iX<<","<<m_iY<<endl;

};

int Coordinate::getX(){

return m_iX;

};


int Coordinate::getY(){

return m_iY;

};

void Coordinate::setX(int x)

{

m_iX = x;

};

void Coordinate::setY(int y)

{

m_iY = y;

 };


测试:

#include "Coordinate.h"


#include <iostream>


using namespace std;


int main(void)

{

Coordinate coo(1,3);

cout<<coo.getX()<<","<<coo.getY()<<endl;

-coo;

cout<<coo.getX()<<","<<coo.getY()<<endl;

return 0;

}

结果:

http://img2.sycdn.imooc.com/59dcc61b0001cbd906750418.jpg

正在回答

1 回答

/*头文件中的成员函数的运算符重载要注释掉,你同时定义了友元操作符重载和成员函数操作符重载,只需要保留一个*/
class Coordinate
{
friend Coordinate &operator-(Coordinate &c);
public: 
Coordinate();
Coordinate(int x,int y);
/*Coordinate &operator-();*/
~Coordinate();
int getX();
void setX(int x);
int getY();
void setY(int y);
private:
int m_iX;
int m_iY;
 };


1 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之模板篇
  • 参与学习       91156    人
  • 解答问题       318    个

本C++教程力求即学即会,所有知识以实践方式讲解到操作层面

进入课程

error C2593: 'operator -' is ambiguous

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信