當我運行該程序,我得到的垃圾值,而不是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;
}
您永遠不會更新成員變量'potion_charges',因此它包含垃圾值,因爲它是未初始化的。 – Rakete1111
發佈文字,而不是文字圖片。 – melpomene