运算符重载+用于字符串连接

时间:2015-04-15 02:49:56

标签: c++ inheritance operator-overloading

我正面临问题'+'运算符重载以进行字符串连接。 这是代码。

#include <iostream>
#include <cstring>
#include <new>

 using namespace std;

class kinda
{
int a;


    public: 
        char *name;
    kinda()
    {
        //cout<<"in base class constr"<<endl;
        a=100;
        name=new char[strlen("sumnesumne")+1];  
        strcpy(name,"sumne");
        //name="sumne";
    }

    ~kinda()
    {
        //cout<<"in base class destr"<<endl;
        delete name;
    }

    kinda(int val,char *naam)
    {
        //cout<<"in base class param constr"<<endl;
        a=val;
        name= new (char) (strlen(naam)+1);
        strcpy(name,naam);
    }

    kinda(kinda &obj)
    {
        //cout<<"in base class copy constr"<<endl;
        a=obj.a;
        name= new (char) (strlen(obj.name)+1);
        strcpy(name,obj.name);
    }

    void display()
    {
        //cout<<"in base class display()"<<endl;
        cout<<"a="<<a<<endl;
        cout<<"name="<<name<<endl<<endl;
    }
};


class kinda2 : public kinda
{

int ab;
public :

kinda2()
{
    //cout<<"in der class default constr"<<endl;
    ab=100;
}

kinda2(int val)
{
    //cout<<"in der class param constr"<<endl;
    ab=val;
}
void dis()
{
    //cout<<"in der class display()"<<endl;
    cout<<"ab : "<<ab <<endl;
    display();
}

kinda2 operator+(const kinda2& ob)
{
    kinda2 retobj;
    //cout<<"in der class op overloading"<<endl;

    retobj.ab= ab + ob.ab;
    cout<<" before : "<< retobj.name<<endl;
    strcpy(retobj.name,name);
    cout<<"middle : "<< retobj.name<<endl;
    strcat(retobj.name,ob.name);
    cout<<"after : "<<retobj.name<<endl;
    return retobj;


}

};

int main()
{
    kinda ob(7,"pachka"),ob1(ob);
    kinda2 ob2,ob3,ob4;

/*  cout<<"ob details:"<<endl;
ob.display();

//ob1(ob);
cout<<"ob1 details:"<<endl;
ob1.display();
*/
    cout<<"ob2 details:"<<endl;
ob2.dis();
cout<<"ob2 details:"<<endl;
ob3.dis();

ob4=ob2+ob3;

ob4.dis();
return 0;
}

代码也涉及简单的继承。

使用'+'运算符重载我试图连接'name'变量。 我得到的输出是:

ob2 details:
ab : 100
a=100
name=sumne

ob2 details:
ab : 100
a=100
name=sumne

 before : sumne
middle : sumne
after : sumnesumne
ab : 200
a=100
name=X☺2


--------------------------------
Process exited with return value 3221226356
Press any key to continue . . .

在运算符重载函数中,它显示正确的值。 但是使用display()我会看到一些意想不到的值。

0 个答案:

没有答案