我有一个简单的Vector类,实现了索引操作符.来自这个和其他相关问题,我不确定为什么以下代码编译:
int main()
{
    const Vector A(5);
    cout << "A :" << A << endl;
    A[0] = 5;
    cout << "A: " << A << endl;
}
Vector.h
#pragma once
#include <iostream> 
#include <functional>
namespace vector
{
    class Vector
    {
        friend std::ostream& operator<<(std::ostream&, const Vector&);
        int n;
        int *arr; 
    public:
        Vector(int = 0); 
        ~Vector();
        Vector(const Vector&);
        Vector& operator=(const Vector&);
    private:
        void copy(const Vector&);
    public:
        int& operator[](const int) const;   
    };
}
Vector.cpp
#include "Vector.h"
#include <algorithm>
#include <utility>
#include <functional>
namespace vector
{ 
    Vector::Vector(int n) : n(n), arr(new int[n])
    {
        std::fill(arr, arr + n, 0);
    }
    Vector::~Vector()
    {
        n = 0;
        delete[] arr;
    }
    void Vector::copy(const Vector& other)
    {
        arr = new int[n = other.n];
        std::copy(other.arr, other.arr + n, arr);
    }
    Vector::Vector(const Vector& other)
    {
        copy(other);
    }
    Vector& Vector::operator=(const Vector& other)
    {
        if (this != &other)  
        {
            this->~Vector();
            copy(other);
        }
        return *this;
    }
    int& Vector::operator[](const int index) const
    {
        return arr[index];
    }
    std::ostream& operator<<(std::ostream& stream, const Vector& vec)
    {
        for (int i = 0; i < vec.n; i++)
            stream << vec.arr[i] << " ";
        return stream;
    }
}
输出:
A: 0 0 0 0 0
A: 5 0 0 0 0
const方法如何返回非const引用(后来用于更改以前的const对象)甚至编译?
son*_*yao 10
简而言之,这是你的责任.
在const成员函数中,只有数据成员本身才会成为const.因为arr(它应该是类型int*)它将成为int * const(即const指针),而不是int const *(即指向const); 即指针变为const但指针不会.因此从技术上讲,可以将非const引用返回给指针,即使它实际上也没有多大意义.
operator[]像大多数STL容器一样,你最好重载一下.例如
// const version
int const & Vector::operator[](const int index) const 
{
    return arr[index]; 
}
// non-const version
int & Vector::operator[](const int index)
{
    return arr[index]; 
}