0

我是 C++ 新手。我想创建银行帐户。我希望第一个创建的银行帐户的帐号为 100000,第二个应该有 100001,第三个应该有 100002,依此类推。我写了一个程序,但“数字”的值没有改变。每个银行帐户都有数字 100000。我不知道如何解决这个问题。

.h-文件

#include <iostream>
#include <string>
using namespace std;
#ifndef _ACCOUNT_H
#define _ACCOUNT_H


class account
{
private:
    string name;
    int accNumber;
    int number= 100000;
    double balance;
    double limit;

public:
    void setLimit(double limit);
    void deposit(double amount);
    bool withdraw(double amount);
    void printBalance();
    account(string name);
    account(string name, double limit);
};

.cpp-文件

#include <iostream>
#include <string>
#include "account.h"
using namespace std;

account::account(string name) {
    this->name= name;
    accNumber= number;
    number++;
    balance= 0;
    limit = 0;
}

account::account(string name, double amount) {
    this->name= name;
    accNumber = number;
    number++;
    balance= 0;
    limit = amount;
}

void account::setLimit(double limit) {
    this->limit = limit;
}
.
.
.
.
.
4

3 回答 3

0

You defined number as a simple member. If you want it to be a class variable, you must change number to

.h-File

class account {
static int number;
};

.cpp-File

int account::number = 100000;
于 2013-11-14T14:44:29.477 回答
0

Make number a static data member, and in your constructor, initialize accNumber with number++.

于 2013-11-14T14:44:31.663 回答
0

您可以使用静态变量来执行此操作。

这是一个例子:

class A {
public:
  A();
  int getId() {
    cout << count_s;
  }
private:
  int id_;
  static int count_s;
}  

A.cpp

int A::count_s = 100000;

A::A() : id_(count_s++) {}
于 2013-11-14T14:45:50.623 回答