重载[]操作符并引用对象本身
Overloaded [] operator and referring to the object itself
我需要在类体内的方法中引用每个顶点。我试过使用this->
, Solid::
等,但也没有很好地出现。
不管怎么说,我把其他的东西都超载了,但是我不能弄清楚,也不能在网上搜索。
#define VERTICES_NR 8
class Solid {
protected:
Vector _vertices[VERTICES_NR];
// ... some other code (does not matter) ... //
public:
void Solid::Move()
{
Vector temp; // <- my own standalone type.
cout << "How would you like to move the solid. Type like "x y z"" << endl;
cin >> temp;
for(int i = 0; i <= VERTICES_NR; i++)
this->[i] = this->[i] + temp;
}
}
我如何实现它?
你可以直接写
for(int i = 0; i < VERTICES_NR; i++)
^^^
_vertices[i] += temp;
如果你想定义下标操作符,它可以像
Vector & operator []( int n )
{
return _vertices[i];
}
const Vector & operator []( int n ) const
{
return _vertices[i];
}
在这种情况下,在类定义中,您可以像
这样使用它operator[]( i )
或
this->operator[]( i )
或
( *this )[i]
直接调用操作符:
operator[](i) += temp;
或通过this
:
(*this)[i] += temp;
可以按其名称显式调用重载操作符函数,如下所示:
operator[](i) = operator[](i) + temp;
错误:您正在访问类对象而不是成员变量vertices_.
<<p> 修正/strong>:for(int i = 0; i <= VERTICES_NR; i++)
vertices_[i] = vertices_[i] + temp;
可以优化为
vertices_[i] += temp;
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 通过向构造函数其他对象引用页面来创建对象
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- C++ 未定义的对象引用
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C :将对象引用作为参数给出错误:呼叫class :: function()的匹配函数
- C++OOP基础知识-是否正确返回对象引用
- 使用对象引用(可能)在调用destructor后使用对象引用
- 创建返回对象引用的成员函数的最简单方法
- 如何在C++上使用对象引用删除对象
- JNI/Android NDK-维护全局对象引用
- 为什么有些类方法返回"*this"(self的对象引用)?
- 在C++中返回伪对象引用的规则