【问题标题】:Overloading [] operator of Matrix class with const [duplicate]用 const 重载 Matrix 类的 [] 运算符 [重复]
【发布时间】:2020-11-08 11:47:16
【问题描述】:

我在尝试理解以下内容时遇到了一些麻烦。 在使用 vector 和模板编写一个简单的 Matrix 类时,我尝试重载 [] 运算符以访问元素。这是课

#pragma once
#include <vector>
#include <iostream>

template <typename T>
class Matrix
{
private:
    std::vector<std::vector<T>> values;
    int rows, cols;
public:
    Matrix(int row, int col) : rows(row), cols(col) {
        values = std::vector<std::vector<T>>(rows, std::vector<T>(cols));
    }

    std::vector<T>& operator[] (const int i) const{
        return values[i];
    }
};

请注意,我返回的是 vector&lt;T&gt;,因此我可以轻松使用双索引。 我遇到的问题是,在尝试调用操作员时,出现以下错误:

Cannot realize the conversion from 'const_Ty' to 'std::vector&lt;T,std::allocator&lt;T&gt;&gt; &amp;

而且我不知道这种转换发生在哪里。我没有修改课堂上的任何内容,所以我认为我应该使用const。

【问题讨论】:

    标签: c++


    【解决方案1】:

    方法为const表示成员变量被视为const,不能修改。

    您当前返回的是 std::vector&lt;T&gt;&amp;,这意味着调用者可以修改它(但这违反了 const 限定符)。

    将返回类型改为const std::vector&lt;T&gt;&amp;,这样调用者就不能修改返回值了。

    【讨论】:

    • 能否请您更明确一点?我看到它有效,但我认为这个答案并不能说明它为什么有效。
    • 说“const 的方法意味着成员变量被视为 const”可能更准确。因此,您不能返回对 values 的非常量引用。
    • 感谢您的解释,现在说得通了。不知道为什么帖子现在被关闭了,虽然
    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多