Wenn ich das Programm laufen bekomme ich Müll Werte anstelle von 2 und 4 und 6.Mysterious int Wert von Standardkonstruktors
-858993460
-858993460
Sum of potion charges: -858993460Press any key to continue . . .
Ich kann nicht sehen, warum der Konstruktor alles andere als die Parameter initialisieren würde ich gab in Main.
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;
}
Sie aktualisieren nie die Mitgliedsvariable 'trank_charges' und daher enthält sie ungültige Werte, da sie nicht initialisiert ist. – Rakete1111
Beitragstext, keine Bilder von Text. – melpomene