繁体   English   中英

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

[英]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 中使用运算符,一切都很好。 它可以正常编译,没有错误。

但是,一旦我在我的主要 function (使用 std::cout 和 std::endl)中执行此操作:

cout << a[0] << endl;

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

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM