Ale*_*lli 279
是的,struct是完全一样class,除了默认的可访问性public的struct(虽然它private的class).
Suv*_*apa 116
是.默认情况下继承是公共的.
语法(示例):
struct A { };
struct B : A { };
struct C : B { };
Run Code Online (Sandbox Code Playgroud)
Cha*_*ing 43
除了Alex和Evan已经说过的内容之外,我想补充一点,C++结构不像C结构.
在C++中,struct可以像C++类一样拥有方法,继承等.
小智 19
在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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
是的,c ++ struct 与 c ++ class 非常相似,除了所有内容都是公共继承(单/多级/分层继承,但不是混合和多重继承)这里是演示代码
#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 30Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128852 次 |
| 最近记录: |