【问题标题】:Non-static data member initializers only available with -std=c++11 or -std=gnu++11非静态数据成员初始化器仅适用于 -std=c++11 或 -std=gnu++11
【发布时间】:2020-08-23 03:53:32
【问题描述】:

[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;
}

另外,我没有包含整个代码,因为它有点长。请告诉我是否需要上传整个代码。只需要帮助以使代码在没有任何错误的情况下运行。

【问题讨论】:

  • Default member initializers 仅从 C++11 开始受支持。换句话说,代码将无法在 C++03 或 C++98 模式下编译。要使警告静音,您需要告诉编译器您打算使用 C++11 语言标准,大概是通过添加适用的 -std 开关。
  • 只是作为提示和供将来参考,出于可读性原因,请缩进您的代码...
  • 我使用良好的缩进实践编辑了您的代码,以使您的代码结构有助于使其具有可读性,这一点非常重要,尤其是在其他人阅读、审查或编辑您的代码时。

标签: c++


【解决方案1】:
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)
{
   //..
}

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2014-10-09
    相关资源
    最近更新 更多