C++ 运算符重载 [] 和 return 类型

C++ operator overloading [] and return types

我刚刚重温 C++,我对 [] 运算符的重载有疑问,更具体地说,我的程序为何无法运行。

在 vec.cpp 中给出以下代码:

double Vec::operator[](unsigned int i) const {
    return this->values[i];
}

double & Vec::operator[](unsigned int i) {
    return this->values[i];
}

这些在 vec.h 中定义为 Vec class 的方法,如果我不在我的 main.cpp 中使用运算符,一切都很好。它编译正常,没有错误。

然而,一旦我在我的主要功能(使用 std::cout 和 std::endl 中执行此操作):

cout << a[0] << endl;

事情出错了。我得到的错误是一堆

candidate function template not viable: no known conversion from 'Vec' to 'char' for 2nd argument
operator<<(basic_ostream<_CharT, _Traits>& __os, char __cn)

您可以将 'char' 替换为任何原始数据类型。

这是一个工作示例

// In vec.h
#pragma once

#include <string>
#include <iostream>

class Vec {
    private:
        int dims;
        double *values;
    public:
        Vec(int dims, double values[]);
        double operator [](unsigned int i) const;
        double& operator[](unsigned int i);
};
// In vec.cpp
#include <iostream>
#include <string>
#include <cmath>

#include "vec.h"

using std::cerr, std::endl, std::cout;

Vec::Vec(int dims, double values[]) {
    this->dims = dims;
    this->values = new double[dims];
    for(int i = 0; i < dims; i++) {
        this->values[i] = values[i];
    }
}

double Vec::operator[](unsigned int i) const {
    if(i >= this->dims) {
        cerr << "Elem out of range" << endl;
    }
    return this->values[i];
}

double & Vec::operator[](unsigned int i) {
    if(i >= this->dims) {
        cerr << "Elem out of range" << endl;
    }
    return this->values[i];
}
// In main.cpp
#include <iostream>
#include <string>

#include "vec.h"

using std::cout, std::endl;

int main() {
    double avals[2];
    avals[0] = 1.0;
    avals[1] = 2.0;
    Vec *a = new Vec(2, avals);

    cout << a[0] << endl; // Error occurs here

    return 0;
}

谁能帮我解决这个问题?

在此声明中

Vec *a = new Vec(2, avals);

声明了一个 Vec * 类型的指针。因此,具有取消引用指针的表达式的类型为 Vec.

所以在这个声明中

cout << a[0] << endl;

表达式 a[0] 的类型为 Vec

你的意思好像是

( *a )[0]

a[0][0]