c++ - 为什么我会收到以下错误 : In constructor 'B::B(int, int)' : no matching function for call to 'A::A()'

标签 c++ inheritance

我收到错误,但不知道哪里出了问题

我试过省略构造函数。

我收到以下错误:

In constructor 'B::B(int, int)': no matching function for call to 'A::A()'

note candidates are:

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 因此它需要构造一个 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) {}   

关于c++ - 为什么我会收到以下错误 : In constructor 'B::B(int, int)' : no matching function for call to 'A::A()' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56384859/

相关文章:

c++ - 类型之间的转换

Swift 在回调中返回 Self

java - 如何在通知中调用父类(super class)方法?

c++ - 如何在不借助 std::function 的情况下存储函数对象?

c++ - 在 C++ 中将十六进制字符串转换为无符号字符

c++ - 未定义结构的静态常量成员

c++ - throw 在 catch 省略号 (...) 中是否会重新抛出 C++ 中的原始错误?

java - 子类是否总是使用父类(super class)的默认构造函数?

java - 如何在Spring Controller 中使用JSON发送继承的对象?

java - 避免让构造函数调用构造函数中的第一个语句