weixin_46029833 2020-06-17 21:55 采纳率: 0%
浏览 78

const修饰的operator[]为什么可以修改字符串,怎么做越界处理比较好

#include <iostream>                                                                        
#include <cstring> 

using namespace std;

class String {
    char *ptrChars;

public:
    String(char const *chars);

    String & operator=(String const &); 
    String & operator=(char const *); 

    char & operator[](const size_t index) const noexecpt(false);

    void print() const;
};

String::String(char const *chars) {
    chars = chars ? chars : ""; 
    ptrChars = new char[strlen(chars) + 1]; 
    strcpy(ptrChars, chars);
}

String & String::operator=(String const &str) {
    if (strlen(ptrChars) != strlen(str.ptrChars)) {
        char *ptrHold = new char[strlen(str.ptrChars) + 1]; 
        delete[] ptrChars;
        ptrChars = ptrHold;
    }   
    strcpy(ptrChars, str.ptrChars);

    return *this;
}

String & String::operator=(char const *ptr) {
    if (strlen(ptrChars) != strlen(ptr)) {
        char *ptrHold = new char[strlen(ptr) + 1]; 
        delete[] ptrChars;
        ptrChars = ptrHold;
    }   
    strcpy(ptrChars, ptr);

    return *this;
}

char & String::operator[](const size_t index) const noexcept(false) {
    /* throw "out of range"; */
        return ptrChars[index];
}

void String::print() const {
    cout << ptrChars << endl;
}

int main()
{
    s = "Cat";
    s.print();
    s[0] = 'a'; // 为什么可以
    s.print();
        cout << s[10] << endl; // 怎么做越界处理
    return 0;
}

关于,operator= 这个函数有两个问题

  1. 怎么做越界处理比较好, throw就直接退出来了,有没有就是给出提示然后接着运行的
  2. 加了const了,为什么还能修改s[0] = a
  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2020-06-18 00:07
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条