下标运算符的重载 test

//
// Created by 刘彪 on 2020/2/29.
//

#include <iostream>
#include <string.h>
#include <cstdio>

using namespace std;
class words{
    char *str;
public:
    words(char *s){
        str = new char[strlen(s)+1];
        strcpy(str,s);
    }
    void disp(){
        cout<<str<<endl;
    }
    char &operator[](int i){
        return *(str+i);
    }
};

int main(){
    char *s = "china";
    words word(s);
    word.disp();
    int n = strlen(s);
    while(n>=0){
        word[n-1] = word[n-1]-32;
        n--;
    }
    word.disp();
    return 0;
}



// 下标运算符的重载 p138
#include <iostream>
#include <string.h>
#include <cstdio>

using namespace std;
class words{
    int len;
    char *str;
public:
    words(char *s){
        str = new char[strlen(s)+1];
        strcpy(str,s);
        len = strlen(s);
    }
    void disp(){
        cout<<str<<endl;
    }
    char operator[](int i){
        if(i>len-1){
            cout<<"数组下标越界";
            return ' ';
        }
        else return *(str+i);
    }
};

int main(){
    words word("Goodbye");
    word.disp();
    cout<<"位置1:";
    cout << word[1] << endl;
    cout<<"位置15:";
    cout << word[15] << endl;
    return 0;
}



// 下标运算符的重载 p155  自己:类首字母大写


全部评论

相关推荐

10-28 17:30
已编辑
华东交通大学 Java
iori2333:这太正常了 我字节面了四五轮 没有一次是在官网投递 都是hr主动捞
秋招笔试记录
点赞 评论 收藏
分享
不想做程序员:稍微看下岗位描述,先过面试再问
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务