【问题标题】:How can I inherit class in C++? [duplicate]如何在 C++ 中继承类? [复制]
【发布时间】:2020-09-25 13:24:47
【问题描述】:

我已使用此代码将 A 类与 B 类继承。

#include <iostream>
#include <string.h>
#include <bits/stdc++.h>
using namespace std;

class A {
    int a,b,c;
    public:
    A(int x, int y, int z) {
      a=x;
      b=y;
      c=z;
    }
    void honk() {
      a+=5;
      b+=5;
      c+=5;
    }
 };


class B: public A {
  public:
      int p;

};

int main() {
    A ob1(10, 12, 13);

  B obj;
  obj.honk();
  cout << A.a + " " + A.b + " " + A.c;
  return 0;
}

这是一个错误错误:没有匹配的函数来调用 A::A()

我该如何解决这个问题? TIA。

【问题讨论】:

标签: c++ oop inheritance


【解决方案1】:

class A 没有定义默认构造函数。您只定义了A(int x, int y, int z)。例如以下将失败:

A myvar; // declaration with default constructor (which doesn't exist)

不过这样就好了:

A myvar(1, 2, 3);

B 构造 A 时,情况相同。 B 在其初始化期间需要使用有效的 A 构造函数。

这里有一些解决方案:

class B: public A {
  public:
      // 1. This forwards constructor arguments from B to A.
      B(int x, int y, int z) :
          A(x, y, z)
      {
      }

      // 2. This conforms to your example;
      //    default constructor of B passes
      //    its own arguments to A
      B() :
          A(1, 2, 3)
      {
      }

      int p;

};

【讨论】:

  • B obj; 将导致此代码出错。
  • 我想给A类对象的变量加5。但是它给B类对象的变量加5
猜你喜欢
  • 2015-03-17
  • 2020-06-01
  • 2020-04-21
  • 2015-11-16
  • 2016-11-14
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
相关资源
最近更新 更多