2016-12-15 70 views
-2

我是新的C++,我想總結兩個對象感謝運算符重載,但問題是我的程序在程序運行期間崩潰,我不知道在哪裏可能是我必須解決的問題,以便很好地編譯我的代碼。運算符重載+爲了總計兩個對象

主要

#include <iostream> 
#include <string> 
#include "Personnage.h" 

int main() 
{ 
    Personnage rony(32), marc(20); 
    Personnage resultat; 

    resultat = rony + marc; 


    system("PAUSE"); 
    return 0; 
} 

Personnage.h

class Personnage 
{ 
public: 
    Personnage(); 
    Personnage(int force); 
private: 
    int power; 
}; 
Personnage operator+(Personnage const& first, Personnage const& second); 

Personnage.cpp

#include "Personnage.h" 
#include <string> 

Personnage::Personnage() : power(0) 
{ 

} 
Personnage::Personnage(int force) : power(force) 
{ 

} 
Personnage operator+(Personnage const& first, Personnage const& second) 
{ 
    Personnage resultat; 
    resultat = first + second; 

    return resultat; 

} 

感謝您的幫助!

+1

你調試過嗎? –

回答

3

問題是您的操作員無休止地自行調用。此聲明:

resultat = first + second; 

......調用您的運算符,然後再次執行該語句,等等等等。最終,您將得到堆棧溢出。

您的operator+需要決定在語義上是什麼意思將兩個Personnage加在一起。例如

Personnage operator+(Personnage const& first, Personnage const& second) 
{ 
    int total_power = first.power + second.power; 
    return Personnage(total_power); 
} 

要訪問私有成員,通常你可以在類中聲明重載運營商friend

class Personnage 
{ 
public: 
    Personnage(); 
    Personnage(int force); 

    friend Personnage operator+(Personnage const& first, Personnage const& second); 

private: 
    int power; 
}; 
+0

這是行不通的,因爲可變權力是私人的,而操作員在課堂之外 –

+0

然後把操作員放到班級 – rlam12

+1

由於我的答案與你的答案几乎相同(但未更新以處理朋友問題),所以我剛剛這是不同的,並在上面添加它。 –

0

將其更改爲

friend Personnage operator+(Personnage const& first, Personnage const& second) 
{ 
    Personnage resultat; 
    resultat.power = first.power + second.power; 

    return resultat; 

} 

friend Personnage operator+(Personnage const& first, Personnage const& second) 
{ 
    Personnage resultat(first.power + second.power); 
    return resultat; 
} 

friend Personnage operator+(Personnage const& first, Personnage const& second) 
{ 
    return (Personnage resultat(first.power + second.power)); 
} 

另外聲明爲在h文件friend

全部相同,只是對不同類型的構造函數的不同調用。