在复制构造函数中明确地确定值时出错

时间:2018-03-17 11:52:06

标签: c++ string class operator-overloading assignment-operator

这里我尝试使用重载的operator +添加两个字符串,但是当明确指定值时,它不会打印所需的输出。

#include <iostream>
#include <cstring>
using namespace std;

class st{

char *p;
int len;

public:
    st(){len=0; p=0;}       //creates null string
    st(const char *s);      //creates string from arrays
    st(const st &s);        //copy constructor
    ~st(){delete p;}        //destructor

    //+ operator
    friend st operator + (const st &, const st &);

    //<= operator
    friend int operator <= (const st &, const st &);
    friend void show(const st);
  };

 st :: st(const char *s){
    len = strlen(s);
    p = new char[len+1];
    strcpy(p, s);
    //cout<<p<<"\n\n";
 }

st :: st(const st &s){
    len = s.len;
    p = new char[len+1];
    strcpy(p, s.p);
    //cout<<p;
 }

//overloading + operator
st operator + (const st &s, const st &t){
    st temp;
    temp.len = s.len + t.len;
    //cout<<temp.len<<" ";
    temp.p = new char[temp.len + 1];

    //cout<<s.p<<" ";
    strcpy(temp.p, s.p);
    //cout<<t.p<<" ";
    strcat(temp.p, t.p);
    //cout<<temp.p<<"\n\n";
    return(temp);
 }

  //overloading <= operator
int operator <= (const st &s, const st &t){
    int m = strlen(s.p);
    int n = strlen(t.p);

   if(m <= n)   return(1);
   else return(0);
}

void show(const st s){
    cout<<s.p;
}


int main(){
    st s1 = "New ";
    st s2 = "York";
    st s3 = "Delhi";
    //st string1=s1, string2=s2, string3=s1+s3;
    st string1, string2, string3;
    string1 = s1;
    string2 = s2;
    string3 = s3+s1;



    cout<<"\nstring1  =  "; show(string1);
    cout<<"\nstring2  =  "; show(string2);
    cout<<endl;
    cout<<"\nstring3  =  "; show(string3);
    cout<<"\n\n";

    if(string1 <= string2){
        show(string1);  cout<<" smaller than "; show(string2);
        cout<<endl;
    }else {
        show(string2);  cout<<" smaller than "; show(string2);
        cout<<endl;
    }

    return 0;
}

如上所述,当我用

运行它时
st string1=s1, string2=s2, string3=s1+s3;

它给出了预期的输出,但当我用

尝试时
st string1, string2, string3;

它打印一些随机字符串

2 个答案:

答案 0 :(得分:0)

您尚未定义operator =。因此,使用默认实现,其将每个字段从右手侧对象复制到左手侧对象。这在左侧对象中产生缓冲区指针p的副本,即两个指针指向同一缓冲区。毫无疑问,它会导致不确定的行为。如果需要,您需要定义operator =(或多个重载运算符)。

请注意,st s1 = "New"具有构造函数,因为它是初始化。相比之下,string1 = s1使用operator = (const st&)

答案 1 :(得分:0)

对于初学者,默认构造函数应至少定义为

st() : p( new char[1] ), len( 0 )
{
    *p = '\0';    
}  

否则使用使用默认构造函数创建的对象,例如在复制构造函数或operator +中使用它将导致未定义的行为。

析构函数应定义为

~st(){ delete []p; }

函数show应至少声明为

friend void show(const st &);

或以下方式

friend std::ostream & show( const st &, std::ostream & = std::cout );

或者您可以定义像

这样的朋友操作员
friend std::ostream & operator <<( std::ostream &, const st & );

至于你在问题中描述的问题,你必须至少声明复制赋值运算符

st & operator =( const st & );

并且还需要声明以下赋值运算符

std & operator =( const char * );