2017-01-03 169 views
1

當我運行該程序,我得到的垃圾值,而不是2,4和6神祕int值

-858993460 
-858993460 
Sum of potion charges: -858993460Press any key to continue . . . 

我不明白爲什麼構造函數初始化什麼,但我給了參數主要。

potions.cpp:

#include "stdafx.h" 
#include "potions.h" 


int Potion::getCharges() const 
{ 
    return potion_charges; 
} 

Potion::Potion() 
{ 
    int potion_charges = 0; 
} 

Potion::Potion(int charges) 
{ 
    int potion_charges = charges; 
} 

Potion::~Potion() 
{ 
    ; 
} 

Potion operator+(const Potion &potion_charges1, const Potion &potion_charges2) 
{ 
    return Potion(potion_charges1.potion_charges + potion_charges2.potion_charges); 
} 

potions.h:

#pragma once 
#include "stdafx.h" 
using namespace std; 

#ifndef POTIONS_H 
#define POTIONS_H 

class Potion 
{ 
private: 
    int potion_charges;                 
public: 
    Potion();      // Default constr 
    Potion(int charges);   // Overloaded constr 
    ~Potion();      // Destr 
    int getCharges() const; 
    friend Potion operator+(const Potion &potion_charges1, const Potion &potion_charges2); 
}; 

#endif 

main.cpp中:

#include "stdafx.h" 
#include "potions.h" 
#include <iostream> 

int main() 
{ 
    Potion potion1(2); 
    Potion potion2(4); 
    Potion potion3 = potion1 + potion2; 
    cout << potion1.getCharges() << endl 
     << potion2.getCharges() << endl; 
    cout << "Sum of potion charges: " << potion3.getCharges(); 
    system("PAUSE");  
    return 0; 
} 
+1

您永遠不會更新成員變量'potion_charges',因此它包含垃圾值,因爲它是未初始化的。 – Rakete1111

+0

發佈文字,而不是文字圖片。 – melpomene

回答

3

構造函數裏面

Potion::Potion() 
{ 
    int potion_charges = 0; 
} 
Potion::Potion(int charges) 
{ 
    int potion_charges = charges; 
} 

您正在定義和初始化名爲potion_charges的局部變量,它們與成員變量potion_charges無關;成員potion_charges根本沒有初始化。

他們更改爲:

​​

或者使用member initializer list

Potion::Potion() : potion_charges(0) {} 
Potion::Potion(int charges) : potion_charges(charges) {} 
+0

謝謝,這清除了它。 –

2

songyuanyao說。你永遠不會更新你的成員變量,只有一個具有相同名稱的本地變量。

我建議你清理你的類定義,並用現代的編譯器構建它:

class Potion 
{ 
private: 
    int potion_charges = 0; // Follows the c++ core guidelines. The default value 
          // is in the class definition itself.                
public: 
    Potion(int charges) : potion_charges(charges) 
    {} 
    int getCharges() const; 
    friend Potion operator+(const Potion &potion_charges1, const Potion &potion_charges2); 
}; 

你的類也並不需要用戶定義的析構函數,因爲它管理任何資源。它通常是最好遵循Rule of Zero/Three/Five

+0

不幸的是VS2015並沒有給我提供警告,但是要感謝你們兩個人,這是我再也不會犯的一個錯誤:) –

+0

@PaulPawłowski - 可變陰影是合法的C++。所以通常很難讓編譯器提出警告。很高興你在SO上得到了你的幫助。 – StoryTeller

0
Potion::Potion() : potion_charges(0) {} 
Potion::Potion(int charges) : potion_charges(charges) {} 

你potion_charges在構造器是自動變量,而不是提交您的類。