C++如何使函数返回调用它的对象
C++ How to make a function return the object that called it?
这感觉应该很明显,但我已经找了一段时间,肯定没有问对问题。我正在为Vector2D类进行赋值运算符重载。该函数只是将调用对象的x和y坐标转换为参数中传递的向量:
// Vector2D.h
class Vector2D
{
public:
float x, y;
Vector2D();
Vector2D(float x, float y);
.
.
.
Vector2D& operator=(const Vector2D& vec);
.
.
.
}
和
// Vector2D.cpp
.
.
.
Vector2D & Vector2D::operator=(const Vector2D & vec)
{
this->x = vec.x;
this->y = vec.y;
return ? ? ? ? ;
}
.
.
.
我应该返回什么来完成这项工作?我天真地以为return this;
会这么做,但这不是合适的参考。
我天真地认为
return this;
会这么做,但这不是正确的参考。
this
是指向当前对象的指针。要实现您想要的结果,只需取消引用它:*this
。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 检查哪个对象调用了另一个对象的对象方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 从 Base 引用对象调用派生类的成员
- 为什么为未删除的对象调用析构函数?
- Qt c++不会为所有对象调用move_slot.为什么?
- 使用在堆栈上创建的对象调用虚拟函数
- 使用基类对象调用Dervied Class函数
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 从类中的对象调用类中的函数的最佳方法
- 派生对象调用的 Base 方法的模板推导
- 如何使用单个对象调用具有相同名称的两个类函数
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 如果类没有任何成员变量,则通过临时对象调用类的成员函数的开销是多少?
- 如何对动态数组中的某些对象调用析构函数
- 如何从列表中存储的对象调用成员函数
- 从线程内的对象调用静态方法
- 从成员对象调用方法
- 当包含它的对象调用其析构函数时,unique_ptr是否未分配
- 从对象调用成员对象,错误:引用非常量值的初始值必须是左值