【问题标题】:why am I getting the following errors : In constructor 'B::B(int, int)': no matching function for call to 'A::A()'为什么会出现以下错误:在构造函数中'B::B(int, int)': no matching function for call to 'A::A()'
【发布时间】:2019-10-16 11:59:49
【问题描述】:

我遇到了错误,不知道出了什么问题

我试过省略构造函数。

我收到以下错误:

在构造函数'B::B(int, int)'中:没有匹配函数调用'A::A()'

注意候选人是:

A::A(const A&)

A::A(int, int)

#include <iostream> 
using namespace std;

class A{
  public:
         int a;
         int b;
         A(int a1, int b1){
               a=a1; b = b1;
               }
  };

class B : public A {
  public:
         int c;
         int d;
         int e;
         B(int c1=10, int d1=20){
               c=c1; d=d1;
               e = a * b;
               }          
  void show(){
       cout <<"a = "<<a<<endl;
       cout <<"b = "<<b<<endl;
       cout <<"c = "<<c<<endl;
       cout <<"d = "<<d<<endl;
       cout <<"e = "<<e<<endl;
       }
  };

int main() {
  A a(2,2);
  B b;
  b.show();
  return 0;
}

【问题讨论】:

  • 你认为 b.a 和 b.b 的值是多少?

标签: c++ inheritance


【解决方案1】:

B 继承自A,因此它需要构造一个A,但您没有A 的默认构造函数,也没有从B 显式调用A 的构造函数初始化列表。

你需要这样的东西:

B(int c1=10, int d1=20) : A(c1, d1) {
               c=c1; d=d1;
               e = a * b;
               }   

或者使A 默认可构造。

此外,您还应该使用 cde 的初始化列表,而不是分配给构造函数主体中的在这种情况下,最好始终以正确的方式进行操作)

B(int c1=10, int d1=20) : A(c1, d1), c(c1), d(d1), e(a*b) {}   

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2014-10-19
    • 2010-10-11
    • 2015-03-20
    • 2017-01-21
    • 2016-05-24
    • 2020-11-08
    • 2021-10-24
    • 1970-01-01
    相关资源
    最近更新 更多