我有一个简单的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
。