返回非常量引用编译的 Const 方法
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;
};
}
矢量.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
,但指针不会。因此,从技术上讲,可以返回对 pointee 的非常量引用,即使它实际上可能没有多大意义。
你最好像大多数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
。
相关文章:
- 从 const 对象访问非 const 方法
- 为什么我可以调用一个从const方法更改成员的方法
- 使用新的c++返回值语法的Const方法
- const_cast const 方法中的"this"将"this"分配给外部变量?
- const 方法使用引用修改对象
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 返回非常量引用编译的 Const 方法
- C++:无法从 const 方法返回对象的shared_ptr
- 是否可以从 const 方法迭代链表
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- "可变"变量只能由 const 方法之一可变?
- Golang中的const方法
- C++ 逻辑恒常性和 const方法的按值返回
- c++将标志添加到const方法中
- C++防止const方法通过成员指针或引用更改数据
- 为什么 const 方法不覆盖 C++ 中的非 const 方法?
- 如何在const方法中迭代映射
- 为什么没有标准化的方法来避免const方法的代码重复
- 修改 const 方法中的 pointee 值