默认构造函数的神秘int值

时间:2017-01-03 06:18:13

标签: c++ constructor initialization

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

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

我无法理解为什么构造函数会初始化除了我在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;
}

3 个答案:

答案 0 :(得分:3)

构造函数内部

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

您正在定义和初始化名为potion_charges的局部变量,这些变量与成员变量potion_charges无关;成员potion_charges根本没有初始化。

将它们更改为:

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

或使用member initializer list

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

你在构造函数中的potion_charges是自动变量,而不是你班级的档案。