C++中的结构体

在标准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

 

posted @ 2013-05-30 09:18  die  阅读(170)  评论(0编辑  收藏  举报