gpt4 book ai didi

c++ - 来自默认构造函数的神秘 int 值

转载 作者:行者123 更新时间:2023-11-30 01:08:47 24 4
gpt4 key购买 nike

<分区>

当我运行程序时,我得到的是垃圾值,而不是 2、4 和 6。

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

我不明白为什么构造函数会初始化除了我在 main 中提供的参数之外的任何东西。

药水.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);
}

药水.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

主要.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;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com