簡體   English   中英

為什么會出現以下錯誤:在構造函數'B :: B(int,int)'中:沒有匹配的函數可用於調用'A :: A()'

[英]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)'中:沒有匹配的函數可以調用'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所以它需要構建A ,但你沒有為默認的構造函數A你也不顯式調用構造AB的初始化列表。

您需要這樣的東西:

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

或使A默認構造。

另外,您還應該對cde使用初始化列表,而不是在構造函數的主體中分配給in(盡管優化器會在這種情況下進行處理,但最好使用以下形式:一直正確的方式)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM