使用VC6打开考生文件夹proj3下的工程proj3,其中声明了MyString类,它是一个用于表示字符串的类。成员函数reverse将字符串反转,例如“abcde”反转后就成了“edcba”。请补充完整函数reverse。在main函数中给出了一个测试数

admin2020-10-21  17

问题 使用VC6打开考生文件夹proj3下的工程proj3,其中声明了MyString类,它是一个用于表示字符串的类。成员函数reverse将字符串反转,例如“abcde”反转后就成了“edcba”。请补充完整函数reverse。在main函数中给出了一个测试数据,此情况下程序的输出应该是:
    This is a stnng
    gnirts a si sihT
    注意:只需在函数reverse的//**********333**********和//**********666**********之间填入若干语句,不要改动程序中的其他内容。
//MyString.h
#include
using namespace std;
char * dup(eonst char*);
class MyString{
    char*str;
public:
    MyString(const char*s=""):str(dup(s)){}
    MyString(eonst MyString&m):str(dup(m.str)){}
    ~MyString(){delete[]str;}
    void reverse();
    void show(ostream&os=cout)eonst{os<};
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
#include"MyString.h"
void writeToFile(const char*path){
  char full[50];
  strcpy(full,path);
  strcat(full,"out.dat");
  ofstream outfile(fun);
  if(outfile.fail()){eelT<<"打开输出文件失败!";return;}
  MyString ml="This is another string":
  MyString m2("字符串反转演示");
  outfile<  m1.reverse();m2.reverse();
  outfile<  outfile.close();
}

选项

答案Void MyString::reverse() { int i,j; char ch: int len=strlen(str); for(i=0,j=len-1;i
解析 程序定义了MyString类,它包含一个成员:str字符指针;默认构造函数和复制构造函数通过dup()函数,动态分配地址p,将参数拷贝到p指向的内存空间,再使用p初始化str;show()成员函数将str指向的字符串输出;reverse()成员函数将str指向的字符串反转;重载的<<运算符函数调用形参m对象的show()函数输出str指向的字符串。
    main()函数首先构造一个MyStrig类对象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自增l,j自减1,直到i不小于j为止。
转载请注明原文地址:https://jikaoti.com/ti/r2l0FFFM
0

最新回复(0)