运算符 = 回合侧一个按值秒按引用
operator= bout side one by value second by refrence?
Q 是如何做到这种运算符=它将在以下方面工作:
int t = v[3];//her i return by Value
v[3] = 8 ;//她我需要通过引用返回(指向 V[3] add'的指针)
Will V 是一个向量类(在我的例子中是模板类)
template <class T>
T& Vector<T>::operator[](const int Index) const
{
if(Index > -1 && Index < this->Size)
{
return &this->Array[Index];
}
else
{
cerr <<"VECTOR_INVALID_INDEX"<<endl;
return NULL;
}
};
此示例中有几个错误。 this
已经是一个指针。做&this
几乎可以肯定不是你在这里想做的。您遇到的另一个问题是,您返回的引用T
但在这种情况下this
是常量。 this->Array[Index]
是无法绑定到T&
的const T
。添加一个常量并改为返回const T&
。第三,this->Size
没有调用方法Size,你忘记了括号。第四个问题是对 NULL 的引用绑定。您将不得不决定另一种方法。指示无法完成操作的常用方法是引发异常。std::vector::at 从标头 stdexcept 抛出 std::out_of_range。
template <class T>
const T& Vector<T>::operator[](const int Index) const
//^^^ add const here
{
if (Index > -1 && Index < this->Size())
// Add parentheses ^^
{
return this->Array[Index];
// ^ No need for &
}
else
{
throw std::out_of_range("VECTOR_INVALID_INDEX");
}
};
您可能还希望添加一个非 const 版本,因为这对于示例v[3] = 8;
将失败。使用相同的主体定义此方法:
T& Vector<T>::operator[](const int Index);
相关文章:
- 返回一个引用C++中另一个类对象的对象的有效方法
- 返回一个C++引用变量 VS 返回一个变量
- 有没有办法重写一个返回指向 istringstream 的指针的函数,而不是返回一个引用?
- 如何使用只有一个引用参数的可变长度参数列表
- 为什么重载 ostream 的运算符<<需要一个引用"&"?
- C++ const-cast 一个引用
- 嵌套绑定到成员,需要一个指针,得到了一个引用.做什么
- r-Rcpp可以公开一个引用同一类的C++类方法
- 有没有办法获取对 MFC 对话框中所有子窗口或控件的引用,因为我有一个引用该控件的 CWnd 对象
- C++一个引用的多个转发:首先复制,然后移动
- 在C++中,我是否可以声明一个引用,以表明没有任何内容会修改它
- 将一个对象传递给一个引用函数,即面试测试
- 需要解释才能理解一个引用的例子
- 一个好的C++编译器会优化一个引用吗
- 我有一个引用,想调用一个需要 boost::shared_ptr 的函数
- 在C++中有一个引用成员有什么问题?
- *return如何隐式返回一个引用
- 为什么我得到一个未对齐指针的警告,而不是一个引用
- 是否可以在不同位置为一个引用分配不同的值
- 编写一个引用类型的函数,用作l值来处理它的r值