问答题 使用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为止。