[英]Const method returning non-const reference compiles
我有一個簡單的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對象)甚至編譯?
簡而言之,這是你的責任。
在const
成員函數中,只有數據成員本身變為const
。 對於arr
(應該是int*
類型),它將成為int * const
(即const
指針),而不是int const *
(即指向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];
}
方法聲明中的const
僅表示該方法只具有對實例本身的只讀訪問權(就好像它接收const MyType *this
而不是MyType *this
)。 如果arr
是類中int
的指針,則在const
方法中使用時,它將分別被視為int * const
。 但請注意,它與const int *
! 這就是解除引用它產生int&
而不是const &int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.