Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;?_C++_Oop_Inheritance - Fatal编程技术网

C++ 如何在C++;?

C++ 如何在C++;?,c++,oop,inheritance,C++,Oop,Inheritance,我用这段代码继承了类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

我用这段代码继承了类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;
}
#包括
#包括
#包括
使用名称空间std;
甲级{
INTA、b、c;
公众:
A(整数x,整数y,整数z){
a=x;
b=y;
c=z;
}
虚空鸣笛(){
a+=5;
b+=5;
c+=5;
}
};
B类:公共A{
公众:
INTP;
};
int main(){
ob1(10、12、13);
B obj;
obj.honk();

cout
类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;

};

阅读一篇好文章。
#include
是非标准的。请参阅。如果您使用compile with
g++-Wall-Wextra-g
,并学习使用调试器。请从开源项目的源代码中寻找灵感,例如,或,或,
cout
B obj;
这一行将导致此代码错误。我想在o的变量中添加5类的对象,但它将5添加到类B对象的变量中