【问题标题】:Why Removing the default constructor is giving error in the compilation of code in c++?为什么删除默认构造函数会在 C++ 中编译代码时出错?
【发布时间】:2022-01-15 15:44:12
【问题描述】:
#include <iostream>
 
using namespace std;

class BankDeposit {
    int principal;
    int years;
    float interestRate;
    float returnValue;

    public:
    BankDeposit() { } //This is line number 12
    
    BankDeposit(int p, int y, float r); // r can be a value like 0.04
    
    BankDeposit(int p, int y, int r); // r can be a value like 14
    
    void show();
};

BankDeposit::BankDeposit(int p, int y, float r) {
    principal = p;
    years = y;
    interestRate = r;
    returnValue = principal;

    for (int i = 0; i < y; i++) {
        returnValue = returnValue * (1 + interestRate);
    }
}

BankDeposit::BankDeposit(int p, int y, int r) {
    principal = p;
    years = y;
    interestRate = float(r)/100;
    returnValue = principal;

    for (int i = 0; i < y; i++) {
        returnValue = returnValue * (1+interestRate);
    }
}

void BankDeposit::show() {
    cout << endl << "Principal amount was " << principal
         << ". Return value after " << years
         << " years is "<<returnValue << endl;
}

int main() {
    BankDeposit bd1, bd2, bd3;
    int p, y;
    float r;
    int R;
    
    // bd1 = BankDeposit(1, 2, 3);
    // bd1.show();

    cout << "Enter the value of p y and R" << endl;
    cin >> p >> y >> R;
    bd2 = BankDeposit(p, y, R);
    bd2.show();

    return 0;
}

为什么删除或注释掉第 12 行中的代码会导致运行代码出错? 但据我所知,我们正在制作自己的构造函数,那么在代码中需要使用默认构造函数吗?也不在代码中包含默认构造函数是为什么给出错误?

【问题讨论】:

  • BankDeposit bd1, bd2, bd3; 需要一个不带参数或具有所有默认参数的构造函数。 BankDeposit bd2(p, y, R); 可以使用给定的代码。
  • 错误是什么?
  • 你说错误是在运行代码时,但据我所知,错误是在编译时。代码甚至没有编译,没有什么可运行的。
  • 默认 ctor 没有参数。因此,通过使用它,您可以在不向 ctor 传递任何参数的情况下创建对象。就像BankDeposit bd1;。如果没有默认的ctor,这条语句将不会被编译,你会得到一个错误。
  • @Chaitanya Deshmukh:您应该Edit您的帖子并复制/粘贴错误消息。你应该总是这样做,在这个 - 以及所有未来的问题上。如果有错误消息,您应该包含它。另外:请务必阅读 anindiangeek 的回复below。如果您觉得有用,请“点赞”并“接受”它。

标签: c++ function oop constructor


【解决方案1】:
BankDeposit bd1, bd2, bd3;

创建类对象的这一行需要一个构造函数,该构造函数应该是默认构造函数,因为您没有传递任何参数。

编辑:刚刚看到他们已经解释过的问题下的 cmets,此外,通过阅读错误消息可以轻松解决这个问题。你可以在这里了解构造函数:here

【讨论】:

    【解决方案2】:

    如果您在类中实现参数化构造函数,则规则是您的类中还必须具有默认构造函数。这就是您的代码失败的原因。 如果除了默认构造函数之外没有任何构造函数,即使代码中没有默认构造函数,代码也不会失败。

    问题是,首先您通过创建参数化构造函数来覆盖编译器,然后您尝试创建不带参数的对象,为此您需要默认构造函数,因此您必须实现它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2022-12-06
      • 1970-01-01
      • 2016-10-16
      • 2019-05-17
      相关资源
      最近更新 更多