在c++中可以继承结构吗?


当前回答

是的,struct和class完全一样,除了struct的默认可访问性是公共的(而class是私有的)。

其他回答

是的,struct和class完全一样,除了struct的默认可访问性是公共的(而class是私有的)。

当然可以。在c++中,结构体和类几乎是相同的(比如默认为public而不是private就是其中的微小区别)。

是的。默认情况下,继承是公共的。

语法(示例):

struct A { };
struct B : A { };
struct C : B { };

除了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