2010-03-28 191 views
8

我一直在考虑为int变量x和y在私人和运算符重载函数类的“this”指针,问题关于C++

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

什么是具有“袋结果的影响(*此);”那里?。

+5

'operator +'函数是否缺少'return'语句? – 2010-03-28 06:40:17

+3

这看起来不是有效的C++ - 新的是关键字 – Artyom 2010-03-28 08:08:25

+0

如果你想创建操作符,我建议看'Boost.Operators'。他们将类似的操作符分组在一起(如'+ ='和'+'),并且只写一个组给你其他人免费:) – 2010-03-28 14:10:11

回答

10

Bag result(*this)创建调用操作符函数的对象的副本。

实施例,如果有:

sum = op1 + op2; 

然后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; 
2

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

Bag result(*this); 

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

4

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


在结构/类中,this是一个指向自身的指针。因此,*this是整个Bag实例本身的参考。

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

因此,

Bag result(*this); 

使得其自身的副本,然后存储到result。这使得未来2所陈述

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

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

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获得该对象(通过取消引用这个),并且它用于构造(通过复制构造函数)另一个名为的袋子结果

我怀疑这个代码是从一个家庭作业拍摄,所以你可能无法使用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; 
} 
+1

这是写op +()的危险方式 - 第一个参数将被切片,如果在此基础上的函数中有任何多态行为,则不会有。将两个参数设置为const引用并在函数中创建副本会好得多。 – 2010-03-28 09:12:10

+0

@Neil:在函数内复制切片;在你需要改变它之前使用这种模式会更好。另请参阅http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/,它提供了与operator =相同的习惯用法。 – 2010-03-28 14:53:54

2

Bag result(*this);是声明变量result并调用其拷贝构造函数

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

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

表达*this可能看起来有点不安,但仅仅是C++,当你处理&参数通常的恐怖。