首页 > 试题广场 >

分别使用成员函数和友元函数编写程序重载运算符“+”,使该运算

[问答题]

分别使用成员函数和友元函数编写程序重载运算符“+”,使该运算符能实现两个字符串的连接。

推荐

(1) 使用成员函数

#include <iostream>
#include<cstring>
using namespace std;
class s
{
  public:
         s(){ *str = '\0'; }
     s( char *pstr ) { strcpy( str,pstr );
     char *gets() { return str; }
         s operator+( s obj );
  private:
        char str[10];
};
s s::operator+( s obj )
{
  strcat( str,obj.str );
   return str;     //或return *this
}    
int main()
{
 s obj1( "Visual" ),obj2( " C++" ),obj3;
  obj3 = obj1 + obj2;
  cout << obj3.gets() << endl;
}

(2)使用友员函数

#include <iostream>
#include<cstring>
using namespace std;
class s
{ public:
        s(){ *str= '\0'; }
    s( char *pstr ) { strcpy( str,pstr ); }
    char *gets() {  return str; }
        friend s operator+( s obj1,s obj2 );
  private:
        char str[100];
};
s operator+( s obj1,s obj2 )
{
 s tempobj;
   strcat( tempobj.str,obj1.str );
   strcat( tempobj.str,obj2.str );
   return tempobj;
}
int main()
{
 s obj1( "Visual" ),obj2( " C++" ),obj3;
   obj3 = obj1 + obj2;
   cout << obj3.gets() << endl;
}

发表于 2018-05-07 15:13:24 回复(0)