首页 > 解决方案 > 非静态数据成员初始化器仅适用于 -std=c++11 或 -std=gnu++11

问题描述

[Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11

下面我曾经//展示了我得到错误的三行代码,尽管代码工作正常。

#include <iostream>
#include <conio.h>

using namespace std;

class Bank
{
  private:
    char name[20];
    int accNo;
    char x;
    double balance;
    double amount;
    float interestRate;
    float servCharge = 5;  //[Warning]
    float count = 0;  //[Warning] 
    bool status = true;  //[Warning]

  public:
    void openAccount();
    void depositMoney();
    void withdrawMoney();
    void checkBalance_info();
    void calcInt();
    void monthlyProc();
};

void Bank::calcInt() {
cout << " Enter your annual interestRate : " << endl;
cin >> interestRate;

double monthlyInterestRate = interestRate / 12;
double monthlyInterest = balance * monthlyInterestRate;
balance += monthlyInterest;

cout << "Updated Balance After Monthly interestRate " << balance << endl;

if (balance < 25){
   status = true;
}

void Bank :: monthlyProc(){  
  if (balance < 25){
    status = false;
  }   
  while (count > 4){
    balance = balance - 1;
  }
  servCharge = servCharge + (count * 0.10);
  balance -= servCharge;
  cout << "Monthly Service Charges: " << servCharge <<endl;
  cout << "Updated Balance After Monthly interestRate " << balance << endl;
}

另外,我没有包含整个代码,因为它有点长。请告诉我是否需要上传整个代码。只需要帮助以使代码运行而不会出现任何错误。

标签: c++

解决方案


float servCharge = 5; //[Warning]

float count = 0;//[Warning] 

bool status = true;//[Warning]

这些是警告,而不是错误。这意味着您正在类中初始化这些成员变量,但它们不是静态成员。这是旧 C++98 和 C++03 的限制。

您可以通过两种方式消除这些警告:

(1) 完全按照编译器的要求执行,即在编译代码时指定这些选项:

-std=c++11 or -std=gnu++11  // using newer C++11

(2) 初始化那些类内定义,而不是使用旧方式初始化它们,即。使用构造函数:

Bank::Bank() : servCharge(5), count(0), status(true)
{
   //..
}

推荐阅读