C / C ++结构与类
在C++中,结构和类基本相同。但是有一些细微的差异。这些差异如下所示。
默认情况下,类成员是私有的,但是结构的成员是公共的。让我们看一下这两个代码,以了解不同之处。
示例
#include <iostream>
using namespace std;
class my_class {
int x = 10;
};
int main() {
my_class my_ob;
cout << my_ob.x;
}输出结果
This program will not be compiled. It will generate compile time error for the private data member.
示例
#include <iostream>
using namespace std;
struct my_struct {
int x = 10;
};
int main() {
my_struct my_ob;
cout << my_ob.x;
}输出结果
10
当我们从类或结构派生结构时,该基类的默认访问说明是公共的,但是当我们派生一个类时,默认访问说明是私有的。
示例
#include <iostream>
using namespace std;
class my_base_class {
public:
int x = 10;
};
class my_derived_class : my_base_class {
};
int main() {
my_derived_class d;
cout << d.x;
}输出结果
This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
示例
#include <iostream>
using namespace std;
class my_base_class {
public:
int x = 10;
};
struct my_derived_struct : my_base_class {
};
int main() {
my_derived_struct d;
cout << d.x;
}输出结果
10
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练