0
点赞
收藏
分享

微信扫一扫

类与对象 重载 实验十三 期末回顾


实验题目录:​​点击打开链接​​



1.第一题

1、阅读程序,其中s::connect函数实现字符串连接。把这个成员函数改写为重载+运算符函数,并修改main函数的对应代码,使其正确运行。

#include <iostream>
#include<cstring>
using namespace std;
class s
{ public:
s() { *str = '\0'; len = 0; }
s( char *pstr )
{ strcpy_s( str,pstr ); len = strlen(pstr); }
char *gets() { return str; }
int getLen() { return len; }
s connect( s obj ); //字符串连接函数声明
private:
char str[100];
int len;
};
s s::connect( s obj ) //字符串连接函数定义
{ strcat_s( str,obj.str );
return str;
}
int main()
{ s obj1( "Visual" ), obj2( " C++" ), obj3(" language");
obj3 = (obj1.connect(obj2)).connect(obj3); //调用字符串连接函数
cout << "obj3.str = "<<obj3.gets() << endl;
cout<<"obj3.len = "<<obj3.getLen()<<endl;
return 0;
}

友元函数重载:

#include <iostream>
#include<cstring>
using namespace std;
class s
{ public:
s() { *str = '\0'; len = 0; }
s( char *pstr )
{ strcpy( str,pstr ); len = strlen(pstr); }
char *gets() { return str; }
int getLen() { return len; }
friend s &operator +(s&a,s&b) //注意operator前有&
{
strcat(a.str,b.str);
a.len = strlen(a.str);
return a;
}
private:
char str[100];
int len;
};
int main()
{ s obj1( "Visual" ), obj2( " C++" ), obj3(" language");
obj3 =obj1+obj2+obj3; //调用字符串连接函数
cout << "obj3.str = "<<obj3.gets() << endl;
cout<<"obj3.len = "<<obj3.getLen()<<endl;
return 0;
}

成员函数重载:

#include <iostream>
#include<cstring>
using namespace std;
class s
{ public:
s()
{ *str = '\0'; len = 0; }
s( char *pstr )
{ strcpy( str,pstr );
len = strlen(pstr);

}
char *gets()
{ return str; }
int getLen()
{ return len; }
s operator+( s obj );
private:
char str[100];
int len;
};
s s::operator+(s obj )
{
strcat( str,obj.str );
return str;
}
int main()
{
s obj1( "Visual" ), obj2( " C++" ), obj3(" language");
obj3 = obj1 + obj2 + obj3;
cout << "obj3.str = "<<obj3.gets() << endl;
cout<<"obj3.len = "<<obj3.getLen()<<endl;
return 0;
}

2.第二题

2、改写下述程序中的student类,用重载运算符>>函数代替input函数;用重载运算符<<函数代替output函数;并修改main函数,使其得到正确的运行结果。

#include <iostream>
using namespace std;
class student
{ char name[20];
unsigned id;
double score;
public:
student(char s[20]="\0", unsigned k=0, double t=0)
{ strcpy_s(name,s);
id=k;
score=t;
}
void input()
{ cout<<"name? ";
cin>>name;
cout<<"id? ";
cin>>id;
cout<<"score? ";
cin>>score; }


void output()
{ cout<<"name: "<<name<<"\tid: "<<id<<"\tscore: "<<score<<endl; }
};
int main()
{ student s;
s.input();
s.output();
return 0;
}

实现代码:

#include <iostream>
#include<cstring>
using namespace std;
class student
{ char name[20];
unsigned id;
double score;
public:
student(char s[20]="\0", unsigned k=0, double t=0)
{ strcpy(name,s);
id=k;
score=t;
}
friend istream& operator>>(istream&input,student&s)
{
cout<<"name? ";
input>>s.name;
cout<<"id? ";
input>>s.id;
cout<<"score? ";
input>>s.score;
return input;
}

friend ostream& operator<<(ostream&output,student&s)
{
output<<"name: "<<s.name<<"\tid: "<<s.id<<"\tscore: "<<s.score<<endl;
return output;
}

};
int main()
{ student s;
cin>>s;
cout<<s;
return 0;
}


举报

相关推荐

0 条评论