在C中的结构体和C++的类绝对是有区别的。
面向过程的C不存在封装的功能,所以结构体的所有成员变量都是public类型的,并且内部不能有函数(成员函数)。
但是如果是作为C++中的结构体和类,他们之间的区别就没有那么大了。
C++为了兼容C,让结构体和类尽可能的相似,现在的结构体也可以存在成员函数、private、protected、public、虚函数等内容,但是还是有细微的区别。
1.继承方面,类的默认继承方式是私有继承 private的,如果想改变要手动写成public继承方式等。但是struct结构体的默认继承方式是public继承。
非常牛逼的一点,类和结构体之间可以相互继承,继承的方式需要看子节点,如果子节点是类,在继承的时候就是私有继承。如果子节点是结构体,在继承的时候就是公有继承。
2.数据的访问问题,类中的成员函数和成员变量在访问时如果不加声明是私有类型的,但是结构体中的成员函数和成员变量在访问时是共有类型的public
3.有人说类在初始化的时候不能直接用={}的方式,但是结构体可以用这种方式,然而事实上是两者是都可以={}方式赋值的。
#include <iostream>
using namespace std;
struct node {
private:
int a;
public:
int b;
void func () {
cout << b << endl;
}
virtual void func1 () {}
//virtual int func2 () = 0;
};
// ????? 鬼鬼
struct A : node {
};
struct B : private A {
};
// 私有继承
class C : node {
};
// 共有继承
struct D : C {
};
struct test {
int a;
char b;
void func () {
cout << a << endl;
cout << b << endl;
}
/*
test () {
cout << "struct test Create Function " << endl;
}
/**/
};
class test1 {
public:
int a;
char b;
void func () {
cout << a << endl;
cout << b << endl;
}
};
class visit {
int a;
void func () {
cout << a << endl;
}
};
struct visit1 {
int b;
void func () {
cout << b << endl;
}
};
int main ()
{
struct node _node;
//_node.a = 1;
_node.b = 2;
_node.func ();
struct A a ;
a.b = 3;
a.func ();
test _test = {1, '1'};
test1 _test1 = {2, '2'};
_test.func ();
_test1.func ();
visit _visit;
visit1 _visit1;
//_visit.func (); // 类中的成员变量和成员函数都是私有类型的
_visit1.func (); // 但是结构体中的数据默认类型是共有类型的
return 0;
}