编者:李国帅
qq:9611153 微信lgs9611153
时间:2011-11-18
自己在结构体的理解方面还是存在偏差的,结构体也是有构造和析构函数的。想当然的认为它没有面向对象的特征是不对的。
公认区别:
从语法上,在C++中(只讨论C++中), class和struct做类型定义时的区别:
(一)默认继承权限。如果不明确指定,来自class的继承按照private继承处理,来自struct的继承按照public继承处理;
(二)成员的默认访问权限。class的成员默认是private权限,struct默认是public权限。
(三)类是面向对象的,可以封装各种函数,而且有自己的构造和析构函数,它是结构类型的自然延伸 。而结构是建立了用于声明变量的一种新的数据类型,编译器不为结构定义保留内存空间,但却为类分配。
例子:
#include <iostream>
using namespace std;
#include <Windows.h>
struct/*class*/ xx
{
public:
xx()
{
m_x = 1;
cout<<1<<endl;
}
xx(int x)
{
m_x = x;
cout<<x<<endl;
}
//~xx(){
virtual ~xx(){
cout<<m_x<<endl;
}
_inline int print1()//隐式内联函数,有的书中说不能包含开关和选择语句,但是这里可以。
{
switch(m_x)
{
case 1:
cout<<"switch 1"<<endl;
break;
}
if (m_x == 1)
{
cout<<"this is 1"<<endl;
}
else
{
cout<<m_x<<endl;
}
return 0;
}
int m_x;
};
struct yy:public xx //继承
{
int f(){
m_x = 200;
cout<<m_x<<endl;
return 0;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
xx x1;
x1.print1();
xx x2(100);
x2.print1();
yy y1;
y1.f();
y1.print1();
system("pause");
return 0;
}