在使用包含 class 的动态实例化后调用 c++ 重载运算符 [] 似乎不起作用

Calling c++ overloaded operator[] after using dynamic instantiation of the containing class doesn't seem to work

我是 C++ 新手,有 Java 和 C# 背景。我刚刚写了一些代码来稍微熟悉一下 C++ 中的异常:

#include<iostream>
#include<string>
using namespace std;


class MyException
{
public:
    MyException(string message)
    {
        this->message = message;
    }

    string& getMessage()
    {
        return this->message;
    }

private:
    string message;
};


class MyClass
{
public:
    MyClass()
    {
        v = new string[2];
        v[0] = "wdeed";
        v[1] = "yyyyyyy";
    }
    ~MyClass()
    {
        delete[] v;
    }
    string& operator[](int index)
    {
        if (index < 0 || index > 1)
            throw MyException("index out of bound exception");

        return v[index];
    }
private:
    string *v;
};


int main()
{
    int index;

    //first option below is not working
    MyClass *myClass = new MyClass();

    //second option works:
    //MyClass myClass;


    cin >> index;
    cout << endl;

    try
    {
        cout << myClass[index];//this is where the error appears
    }
    catch (MyException& ex)
    {
        cout << ex.getMessage();
    }
    catch (...)
    {
        cout << "Other exception";
    }

    return 0;
}

语句 "cout << myClass[index];" 产生错误

仅当我使用动态分配 (MyClass *myClass = new MyClass();) 时出现的错误是:

  1. 没有运算符“<<”匹配这些操作数操作数类型are:std::ostream<

  2. 二进制“<<”: 未找到接受类型为 'MyClass' 的右手操作数的运算符(或没有可接受的转换)

如何修复代码?

MyClass *myClass 是指向 MyClass 对象的指针。因此,您需要在将其用作 MyClass:

之前取消引用它
(*myClass)[index];

但实际上,您根本不需要在这里使用 newmyClass 应该只是一个自动对象(就像你的 commented-out 代码),内部 std::string 动态数组应该是 std::vector<std::string>