分别使用成员函数和友元函数编写程序重载运算符“+”,使该运算符能实现两个字符串的连接。
(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; }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
(1) 使用成员函数
(2)使用友员函数