【问题标题】:Change class variable in constructor for each object created为创建的每个对象更改构造函数中的类变量
【发布时间】:2013-11-14 14:41:10
【问题描述】:

我是 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;
}
.
.
.
.
.

【问题讨论】:

标签: c++ constructor private


【解决方案1】:

您将number 定义为一个简单成员。如果你想让它成为一个类变量,你必须把number改为

.h-文件

class account {
static int number;
};

.cpp-文件

int account::number = 100000;

【讨论】:

    【解决方案2】:

    number 设为static 数据成员,并在构造函数中将accNumber 初始化为number++

    【讨论】:

      【解决方案3】:

      您可以使用静态变量来做到这一点。

      这是一个例子:

      啊.h

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

      【讨论】:

        猜你喜欢
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多