2010-03-28 93 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++,當你處理&參數通常的恐怖。