在c++中可以继承结构吗?
当前回答
除了Alex和Evan已经说过的,我想补充一点,c++结构体与C结构体不同。
在c++中,结构体可以像c++类一样具有方法、继承等。
其他回答
当然可以。在c++中,结构体和类几乎是相同的(比如默认为public而不是private就是其中的微小区别)。
是的。默认情况下,继承是公共的。
语法(示例):
struct A { };
struct B : A { };
struct C : B { };
Yes, c++ struct is very similar to c++ class, except the fact that everything is publicly inherited, ( single / multilevel / hierarchical inheritance, but not hybrid and multiple inheritance ) here is a code for demonstration #include<bits/stdc++.h> using namespace std; struct parent { int data; parent() : data(3){}; // default constructor parent(int x) : data(x){}; // parameterized constructor }; struct child : parent { int a , b; child(): a(1) , b(2){}; // default constructor child(int x, int y) : a(x) , b(y){};// parameterized constructor child(int x, int y,int z) // parameterized constructor { a = x; b = y; data = z; } child(const child &C) // copy constructor { a = C.a; b = C.b; data = C.data; } }; int main() { child c1 , c2(10 , 20), c3(10 , 20, 30), c4(c3); auto print = [](const child &c) { cout<<c.a<<"\t"<<c.b<<"\t"<<c.data<<endl; }; print(c1); print(c2); print(c3); print(c4); } OUTPUT 1 2 3 10 20 3 10 20 30 10 20 30
在c++中,结构的继承和类的继承是一样的,除了以下不同之处:
从类/结构派生结构时,基类/结构的默认访问说明符为public。在派生类时,默认的访问说明符是私有的。
例如,程序1因编译错误而失败,而程序2正常工作。
// Program 1
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // Is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // Compiler error because inheritance is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Base {
public:
int x;
};
struct Derived : Base { }; // Is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // Works fine because inheritance is public
getchar();
return 0;
}
除了Alex和Evan已经说过的,我想补充一点,c++结构体与C结构体不同。
在c++中,结构体可以像c++类一样具有方法、继承等。
推荐文章
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?
- 为什么std::map被实现为红黑树?
- 空括号的默认构造函数