本文介绍了我不明白为什么“返回c“因为我们知道我们可以在构造函数定义中返回一个对象,所以不在复制构造函数定义中工作。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <     iostream    >  
#include < string >
#include < cstring >
使用 namespace std;
class string1
{
char * name;
int 长度;

public
string1()
{
length = 0 ;
name = new char [length + 1 ];
}

string1( char const * s)
{
length = strlen(s);
name = new char [length + 1 ];
strcpy(name,s);
}

void display( void
{
cout<<名称<< ENDL;
}

~string1();
int join( const string1& a, const string1& b);
};

int string1 :: join( const string1& a, const string2& b)
{
string1 c;
c.length = a.length + b.length;
删除名称;
c.name = new char [c.length + 1 ];
strcpy(c.name,a.name);
strcat(c.name,b.name);
return c;
}

string1 :: ~string1()
{
delete name;
}

int main()
{
char const * str1 = myname ;
string1 name1(str1);
string1 name2( anupam);
string1 name3( sinha);
string1 s1;
string1 s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
}
解决方案




#include< iostream > 
#include< string >
#include< cstring >
using namespace std;
class string1
{
  char *name;
  int length;

public:
  string1 ()
  {
    length = 0;
    name = new char[length + 1];
  }
 
  string1 (char const *s)
  {
    length = strlen (s);
    name = new char[length + 1];
    strcpy (name, s);
  }

  void display (void)
  {
    cout << name << endl;
  }

  ~string1();
  int join (const string1 &a, const string1 &b);
};

int string1::join (const string1 &a, const string2 &b)
{
  string1 c;
  c.length = a.length + b.length;
  delete name;
  c.name = new char[c.length + 1];
  strcpy (c.name, a.name);
  strcat (c.name, b.name);
  return c;
}

string1 :: ~string1()
{
  delete name ;
}

int main ()
{
  char const *str1 = "myname ";
  string1 name1 (str1);
  string1 name2 ("anupam ");
  string1 name3 ("sinha ");
  string1 s1;
  string1 s2;
  s1.join (name1, name2);
  s2.join (s1, name3);
  name1.display ();
  name2.display ();
  name3.display ();
  s1.display ();
  s2.display ();
}
解决方案




这篇关于我不明白为什么“返回c“因为我们知道我们可以在构造函数定义中返回一个对象,所以不在复制构造函数定义中工作。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:18