c++ - 返回非 const 引用的 Const 方法编译

标签 c++ constants

我有一个简单的 Vector 类,其中实现了索引运算符。 来自this和其他相关问题,我不确定为什么以下代码可以编译:

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 方法如何编译?

最佳答案

简而言之,这是您的责任。

const成员函数中,只有数据成员本身变成了const。对于 arr(应该是 int* 类型)它将变成 int * const(即 const 指针),而不是 int const *(即指向 const 的指针);即指针变为 const 但指针没有。因此,从技术上讲,可以返回对指针对象的非常量引用,即使实际上它可能没有多大意义。

您最好像大多数 STL 容器一样重载 operator[]。例如

// 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]; 
}

关于c++ - 返回非 const 引用的 Const 方法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48518503/

相关文章:

c++ - 为什么 CToolBar::LoadToolBar 会失败?

c++ - C++中最快的输入法是什么

c++ - 以下是新的重载泄漏内存吗?

c++ - 我在 win32 窗口专用应用程序中创建了一个新控制台,控制台已创建但没有任何内容打印在上面

c++ - 指针和引用作为 const 对象的成员变量

c - 如果我可以通过 C 中的指针修改 const 限定符,那么它的用途是什么?

C++/SDL 'void*' 不是点对对象类型

C 常量表达式。 const 变量作为常量表达式

c++ - 'const' 关键字是如何工作的?

properties - 为 D 中的 const 和非常量结构提供 @property