关于c ++中"this"指针的问题

sil*_*ent 8 c++ class operator-overloading this

我已经给了私有的int变量x和y的类,以及一个运算符重载函数,

class Bag{
private:
    int x;
    int y;
public:
    Bag();
    ~Bag();
    //.......
    //.....etc
};


Bag operator+ (Bag new) const{
    Bag result(*this);   //what does this mean?
    result.x += new.x;         
    result.y += new.y;
}
Run Code Online (Sandbox Code Playgroud)

有"袋子结果(*this);"的效果是什么?那里?.

cod*_*ict 10

Bag result(*this) 创建调用运算符函数的对象的副本.

示例如果有:

sum = op1 + op2; 
Run Code Online (Sandbox Code Playgroud)

然后result将是一份副本op1.

由于operator+函数正在对其操作数求和并返回和,我们需要一种方法来访问通过this指针完成的操作数op1 .

或者我们可以做到:

Bag result;
result.x = (*this).x + newobj.x; // note you are using new which is a keyword.
result.y = (*this).y + newobj.y; // can also do this->y instead
return result;
Run Code Online (Sandbox Code Playgroud)


小智 5

您的代码如下所示:

class Bag {
public:
  Bag();
  Bag(Bag const& other); // copy ctor, declared implicitly if you don't declare it
  ~Bag();

  Bag operator+(Bag const& other) const;

private:
  int x;
  int y;
};

Bag Bag::operator+(Bag const& other) const {
  Bag result (*this);
  result.x += other.x;         
  result.y += other.y;
  return result;
}
Run Code Online (Sandbox Code Playgroud)

成员函数的隐式"当前对象"由名为this的特殊值指向.然后*this获取该对象(通过取消引用),它是用于构建(通过拷贝构造函数),另一个袋子命名结果.

我怀疑这段代码是从家庭作业中获取的,所以你可能无法使用一个真正的加法运算符模式,但它很常见,你应该知道它:

struct Bag {
  //...
  Bag& operator+=(Bag const& other) {
    x += other.x;
    y += other.y;
    return *this; // return a reference to the "current object"
    // as almost all operator=, operator+=, etc. should do
  }
};

Bag operator+(Bag a, Bag const& b) {
  // notice a is passed by value, so it's a copy
  a += b;
  return a;
}
Run Code Online (Sandbox Code Playgroud)