简体   繁体   中英

Change class variable in constructor for each object created

I am new to c++. I want to create bank account. I want the first created bank account to have the account number 100000, the second should have 100001, the third should have 100002 and so on. I wrote a program but the value of "number" doesn't change. Every bank account has the number 100000. I am not sure how to solve the problem.

.h-File

#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-File

#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;
}
.
.
.
.
.

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;

number设为static数据成员,然后在您的构造函数中,使用number++初始化accNumber

You can do this with a static variable.

This is an example:

Ah

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++) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM