在c++中可以继承结构吗?
当前回答
是的,struct和class完全一样,除了struct的默认可访问性是公共的(而class是私有的)。
其他回答
是的,struct和class完全一样,除了struct的默认可访问性是公共的(而class是私有的)。
除了Alex和Evan已经说过的,我想补充一点,c++结构体与C结构体不同。
在c++中,结构体可以像c++类一样具有方法、继承等。
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而不是private就是其中的微小区别)。
是的。默认情况下,继承是公共的。
语法(示例):
struct A { };
struct B : A { };
struct C : B { };
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?