C++ 如何在C++;?
我用这段代码继承了类A和类BC++ 如何在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
#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 withg++-Wall-Wextra-g
,并学习使用调试器。请从开源项目的源代码中寻找灵感,例如,或,或,coutB obj;
这一行将导致此代码错误。我想在o的变量中添加5类的对象,但它将5添加到类B对象的变量中