+ 运算符重载以添加不同的 C++ 类对象 [英] + operator overload to add different C++ class object

查看:43
本文介绍了+ 运算符重载以添加不同的 C++ 类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多添加同一类对象的例子.我试图使用运算符重载来添加两个不同的类对象.代码:

I have seen many example to add objects of same class.I was trying to add two different class objects using operator overloading. Code:

#include<iostream>
using namespace std;
class B;
class A
{
public:
int x;
A(int t=99)
{
x=t;
}
friend const A operator+( A& m, B& n);
friend ostream& operator<<(ostream& os, const A& c);
};

const A operator+(A& c1,B& c2) 
{
     A temp;
     temp.x = c1.x + c2.y; 
         return temp;
 }
 ostream& operator<<(ostream &os, const A& c)
 { 
    os << c.x;
    return os;
}


class B
{
public:
int y;
B(int e=90)
{
y=e;
}
friend const A operator+( A& m, B& n);
};

int main()
{
A a,u;
B b;
u=a+b;
cout<<"Value of A+B"<<u;
return 0;
}   

当我编译我的代码时,它显示错误:

When i compiled my code it shows Error:

$ g++ operator_overloading.cpp

operator_overloading.cpp:在函数‘const A operator+(A&, B&)’中:

operator_overloading.cpp:19:21: 错误:不完整类型‘struct B’的无效使用

operator_overloading.cpp:3:7: 错误:‘struct B’的前向声明

我做错了什么??

推荐答案

必须在定义类 B 之后定义操作符.例如

You have to define the operator after the definition of class B. For example

#include<iostream>
using namespace std;

class B;
class A
{
public:
int x;
A(int t=99)
{
x=t;
}
friend const A operator+( const A& m, const B& n);
friend ostream& operator<<(ostream& os, const A& c);
};

 ostream& operator<<(ostream &os, const A& c)
 { 
    os << c.x;
    return os;
}


class B
{
public:
int y;
B(int e=90)
{
y=e;
}
friend const A operator+( const A& m, const B& n);
};

const A operator+(const A& c1, const B& c2) 
{
     A temp;
     temp.x = c1.x + c2.y; 
         return temp;
 }

 //...

否则编译器不知道类 B 有哪些数据成员.此外,最好将运算符的参数定义为常量引用.在这种情况下,操作员可以处理临时对象.

Otherwise the compiler does not know what data members class B has. Also it is better to define paraneters of the operator as constant references. In this case the operator can deal with temporary objects.

这篇关于+ 运算符重载以添加不同的 C++ 类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆