关于c ++中“this”指针的问题

时间:2010-03-28 06:35:28

标签: 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;
}

有“袋子结果(* this);”的效果是什么?那里?。

5 个答案:

答案 0 :(得分:10)

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

示例如果有:

sum = op1 + op2; 

然后result将是op1的副本。

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

或者我们可以做到:

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;

答案 1 :(得分: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;
}

成员函数的隐式“当前对象”由名为 this 的特殊值指向。然后*this获取该对象(通过解除引用 this ),它用于构建(通过复制构造函数)另一个名为 result 的Bag。

我怀疑这段代码来自家庭作业,所以你可能无法使用one true addition operator模式,但这很常见,你应该知道它:

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;
}

答案 2 :(得分:4)

首先,告诉代码编写者不要使用new作为变量名 - 它是一个关键字。另外,请记住return result;。并通过const-reference传递或直接修改new包。


在struct / class中,this是指向自身的指针。因此,*this是对整个Bag实例本身的引用。

声明Bag result(a_bag_reference)将调用Bag的复制构造函数,该复制构造函数会将a_bag_reference复制到result

因此,

Bag result(*this);

制作自己的副本,然后存储到result。这使得接下来的两个陈述

result.x += new.x;
result.y += new.y;

不影响实例本身(即this->xthis->y保持不变)。

答案 3 :(得分:2)

operator+函数返回一个副本。声明:

Bag result(*this);

正在制作对象的副本以返回给调用者。 根据签名,它必须返回一个值,因此它正在复制然后添加new对象。

答案 4 :(得分:2)

Bag result(*this);声明变量result并调用其复制构造函数

您可以想象C ++会自动为所有类声明一个默认的复制构造函数。它的工作就是使用另一个对象初始化一个对象:

Bag::Bag(Bag const& src) {
   x = src.x;
   y = src.y;
}

表达式*this可能看起来有点令人不安,但在处理&参数时,这只是C ++的常见恐怖。