我班上错了

时间:2015-01-17 01:14:35

标签: c++ function class object constructor

我不知道为什么,但当我用我的类创建一个对象并使用默认构造函数时,当我尝试将名为cash的变量传递给访问者user2.setCash(cash)时,目的是为了主要集{{1等于cash,它会给出一个像new_cash这样的大值。为什么会这样?如果我使用我的重载构造函数,它工作正常。

的main.cpp

1.222256e+461

Bank.h

#include <iostream>
#include <string>
#include "Bank.h"

using namespace std;

int main()
{
    string name;
    int id;
    double cash;

bank user2;
cout << "\n\nPlease type your name: ";
getline(cin >> ws, name);
user2.setName(name);
cout << "Enter an id number: ";
cin >> id;
user2.setID(id);
cout << "Enter your cash: ";
cin >> cash;
cout << cash << endl;
user2.setCash(cash);
cout << "\nAlright " << user2.getName() << ", current cash: " << user2.getCash();
cout << "\nChoose how much would you like to Deposit: ";
cin >> cash;
user2.deposit(cash);
cout << "New amount is: " << user2.getCash() << " For user ID: " << user2.getID() << "\n\n";
bank::printStatic();

return 0;
}

Bank.cpp

#ifndef BANK_H
#define BANK_H

#include <iostream>
#include <string>

using namespace std;

class bank
{
public:
    // Default Constructor
    bank();

    // Overload Constructor
    bank(string, int, double);

    // Destructor
    ~bank();

    // Accessor Functions
    string getName() const;
    int getID() const;
    double getCash() const;

    // Mutator Functions
    void setName(string);
    void setID(int);
    void setCash(double);

    // Functions
    void withdraw(double);
    void deposit(double);
    static void printStatic();

private:
    // Member Variables
    string new_name;
    int new_id;
    double new_cash;

    // Static Member Variables
    static int num_of_accounts;
    static double total_cash;

};

#endif

2 个答案:

答案 0 :(得分:3)

您需要在构造函数中初始化所有基本类型成员。

否则你得到不确定的值

此外,非默认构造函数是错误的:

// Default Constructor
bank::bank()
{
    int new_id = 0; 
    double new_cash = 0.0;
 ....

^设置局部变量的值,而不是成员变量


我建议使用启动列表:

// Default Constructor
bank::bank() : new_name(), new_id(0), new_cash(0.0)
{
    ++num_of_accounts;
}

// Overload Constructor
bank::bank(string name, int id, double cash)
    : new_name(name), new_id(id), new_cash(cash)
{
    ++num_of_accounts;
    total_cash += new_cash;
}

您也可以将两者结合起来:

bank::bank(string name = "", int id = 0, double cash = 0.0)
    : new_name(name), new_id(id), new_cash(cash)
{
    ++num_of_accounts;
    total_cash += new_cash;
}

答案 1 :(得分:-1)

在默认构造函数中,您将声明与成员变量具有相同名称的局部变量。然后,您需要设置这些局部变量,而不是分配成员。摆脱类型声明,以便它们正常分配。

bank::bank()
{
    new_id = 0;
    new_cash = 0.0;
    ++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}