在标准C++中,struct和class有两个区别:第一:struct中的成员默认是public的,class中的默认是private的。第二:在用模版的时候只能写template <class Type>或template <typename Type>不能写template <struct Type>。 C语言的struct 没有 方法,而C++的class是有方法的C语言的struct 没有构造函数和析构函数,而class是有的。struct继承默认是public继承,而class继承默认是private继承
1 写个小例子试一下,可以继承
2
3 #include<iostream>
4 using namespace std;
5
6 struct A
7 {
8 int a;
9 int b;
10 };
11 struct B : A
12 {
13 int c;
14 };
15 void main()
16 {
17 struct B stB;
18 stB.a = 1;
19 cout<<stB.a<<endl;
20 }
View Code
方法参数是父类,你传子类进去,就相当于把子类截断了,数据会丢。
你可以定义方法参数是父类指针,传子类指针进去,然后函数内转化指针为子类类型。
1 #include <iostream>
2 using namespace std;
3 struct A{
4 int x,y,z;
5 };
6 struct B:public A{
7 int a,b,c;
8 };
9 void func(A* pA){
10 cout << pA->x
11 << endl
12 << ((B*)pA)->a
13 << endl;
14 }
15 int main(){
16 B b;
17 b.x=1;
18 b.y=2;
19 b.z=3;
20 b.a=4;
21 b.b=5;
22 b.c=6;
23 func(&b);
24 return 0;
25 }
View Code
原文链接: https://www.cnblogs.com/fvsfvs123/archive/2013/05/30/3107460.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/90559
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!