今天学到类的时候,感觉和之前学的结构体很像,就去百度了结构体和struct的区别。
struct和class默认的访问权限不一样,而且类是有继承的,结构体没有继承。
- C++结构体内部成员变量及成员函数默认的访问级别是public,而c++类的内部成员变量及成员函数的默认访问级别是private。
- C++结构体的继承默认是public,而c++类的继承默认是private。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78#include <iostream>
using namespace std;
struct point
{
public:
point() :x_(0.0), y_(0.0)
{
std::cout << "default constructor point\n";
}
point(double x, double y) :x_(x), y_(y)
{
std::cout << "constructor point(" << x << ", " << y << ")\n";
}
~point()
{
std::cout << "default destructor point\n";
}
double get_x()
{
return x_;
}
double get_y()
{
return y_;
}
private:
double x_;
double y_;
};
class point_class
{
public:
point_class() :x_(0.0), y_(0.0)
{
std::cout << "default constructor point_class\n";
}
point_class(double x, double y) :x_(x), y_(y)
{
std::cout << "constructor point_class(" << x << ", " << y << ")\n";
}
~point_class()
{
std::cout << "default destructor point_class\n";
}
double get_x()
{
return x_;
}
double get_y()
{
return y_;
}
private:
double x_;
double y_;
};
int main()
{
point pt;
std::cout << pt.get_x() << "\n";
std::cout << pt.get_y() << "\n";
std::cout << "sizeof( double ): " << sizeof(double) <<
", sizefof( point ): " << sizeof(point) << "\n";
point_class pt_c;
std::cout << "sizeof( double ): " << sizeof(double) <<
", sizefof( point_class ): " << sizeof(point_class) << "\n";
}
总结:C++中的struct与class比较类似。struct默认访问权限是public,class是private;class有继承,多态机制,而struct没有。