如何在C ++中添加相同类的三个对象? [英] how to add three objects of same class in c++?

查看:40
本文介绍了如何在C ++中添加相同类的三个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在C ++中使用运算符重载添加三个对象吗?

can i add three objects using operator overloading in c++??

#include <iostream>
#include <conio.h>
using namespace std;

class complex{
private:
    int a;
public:
    void setdata(int x){
        a=x;
    }
    void showdata(){
        cout<<"\n"<<a;
    }
    int operator +(complex c,complex d){
        complex temp;
        temp.a=a+c.a+c+d.a;
        return (temp);
    }
};

int main(){
complex c1,c2,c3,c4;
c1.setdata(3);
c2.setdata(5);
c4.setdata(2);
c4=c1+c2+c3;
c4.showdata();
}

我正在使用这种方法,但无法正常工作,请帮忙.

i am using this approach but it is not working please help.

推荐答案

您必须稍微改变一下运算符,并且变量的初始化会出错(未初始化C3).您不必定义同时使用三个术语的运算符.总和将分为两部分(c1 + c2)+ c3;第一个总和返回添加到c3的复杂"项.该最后总和的结果分配给c4.参见下面的代码.

you have to change a little the operator and you have a mistake in the inizialization of the variables (C3 is not initialized). You have not to define an operator that works on three terms at the same time. The sum will be split in two parts (c1 + c2) + c3; the first sum returns a 'complex' item that is added to c3. The result of this last sum is assigned to c4. See below the code.

#include <iostream>
#include <conio.h>
using namespace std;

class complex{
private:
    int a;
public:
    void setdata(int x){
        a = x;
    }
    void showdata(){
        cout << "\n" << a;
    }
    complex operator +(complex c){
        complex temp;
        int i = 0;
        i = a + c.a;
        temp.setdata(i);
        return temp;
    }
};

int main(){
    complex c1, c2, c3, c4;
    c1.setdata(3);
    c2.setdata(5);
    c3.setdata(2);
    c4 = c1 + c2 + c3;
    c4.showdata();
}

这篇关于如何在C ++中添加相同类的三个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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