使用 VC6 打开考生文件夹 proj3 下的工程 proj3, 其中声明了 MyString 类, 它是一个用于表示字符串的类。 成员函数 reverse 将字符串反转, 例如“abcde” 反转后就成了“edcba”。 请补充完整函数 reverse。 在 main 函数中给出了一个测试数据, 此情况下程序的输出应该是:
This is a string
gnirts a si sihT
注意: 只需在函数 reverse 的//********333****和//****666****之间填入若干语句, 不
要改动程序中的其他内容。
//MyString.h
#include<iostream>
using namespace std;
char*dup(const char*);
class MyString{
char*str;
public:
MyString(const char*s=" "):str(dup(s)){}
MyString(const MyString&m):str(dup(m.str)){}
~MyString(){delete[]str;)
void reverse();
void show(ostream&os=cout)const{os<<str<<endl;}
};
inline ostream&operator<<(ostream&os,const MyString&m){
m.show(os);
return os;
}
void writeToFile(const char*path);
//MyString.cpp
#include"MyString.h"
char*dup(const char*s){
char*p=new char[strlen(s)+1];
strcpy(p,s);
return p;
}
void MyString::reverse(){
//********333********
//********666********
}
void writeToFile(const char*path);
//writetoFile.cpp
#include<fstream>
#include"MyString.h"
void writeToFile(const char*path){
char full[50];
strcpy(full,path);
strcat(full,"out.dat");
ofstream outfile(full);
if(outfile.fail()){cerr<<"打开输出文件失败!";return;)
MyString m1="This is another string";
MyString m2("字符串反转演示");
outfile<<m1<<m2;
m1.reverse();
m2.reverse();
outfile<<m1<<m2;
outfile.close();
}
void MyString::reverse()
{
int i,j;
char ch;
int len=strlen(str);
for(i=0,j=len-1;i<j;i++,j--)
{
ch=str[i];
str[i]=str[j];
str[j]=ch;
}
}
本题考查类的数据成员、类的成员函数、重载流运算符>>和插入运算符<<和字符数组。
程序定义了 MyString 类, 它包含一个成员: str 字符指针; 默认构造函数和复制构造函数通过 dup()函数, 动态分配地址 p, 将参数拷贝到 p 指向的内存空间, 再使用 p初始化 str; show()成员函数将 str 指向的字符串输出; reverse()成员函数将 str 指向的字符串反转; 重载的<<运算符函数调用形参 m 对象的 show()函数输出 str 指向的字符串。
main()函数首先构造一个 MyString 类对象 m1, 构造过程中传入字符串“This is a string”,所以 m1 对象中的 str 指向一个动态分配的内存空间, 该段内存存放拷贝的字符串“This is a string”, 输出 m1 后, 再调用 m1.reverse()函数, 将 str 指向的字符串进行反转, 再输出 m1,题意要求我们完成 reverse()成员函数的定义, 完成反转字符串的功能。
由题意, 我们仅有的信息就是 str 指向一个字符串, 它是 char*类型, 需要对 str 指向的字符串进行反转, 需要获得字符串的长度, 然后将首尾字符进行交换, 直到交换到中间字符串为止, 所以我们定义两个变量 i、 j, 表示元素下标, 分别从首(i=0)和尾(长度-1)向中间遍历该字符串, 每次遍历, 首先判断 i 是否小于 j, 若 i 小于 j 则将 i 和 j 下标对应的字符进行交换,交换完成后 i 自增 1, j 自减 1, 直到 i 不小于 j 为止。