从语法上来讲,class和struct做类型定义时只有两点区别:
(1)默认继承权限,如果不指定,来自class的继承按照private继承处理,来自struct的继承按照public继承处理;
(2)成员的默认访问权限。class的成员默认是private权限,struct默认是public权限。以上两点也是struct和class最基本的差别,也是最本质的差别;
但是在C++中,struct进行了扩展,现在它已经不仅仅是一个包含不同数据类型的数据结构
了,它包括了更多的功能;
首先,struct能包含成员函数吗?是的,答案是肯定的。
好的,写一段代码验证一下:
[cpp]
#include "stdafx.h"
struct Test
{
int a;
int getA()
{
return a;
}
void setA(int temp)
{
a = temp;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test testStruct;
testStruct.setA(10);
cout<<"Get the value from struct:"<
Test *testStructPointer = new Test;
testStructPointer->setA(20);
cout<<"Get the value from struct again:"<getA()<
delete testStructPointer;
return 0;
}
以上的代码会很正确的运行,是的;没错,struct能包含成员函数的。
第二,struct有自己的构造函数吗?是的,可以的。
#include "stdafx.h"
struct Test
{
int a;
Test()
{
a = 100;
}
int getA()
{
return a;
}
void setA(int temp)
{
a = temp;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test testStruct;
testStruct.setA(10);
cout<<"Get the value from struct:"<setA(20);
cout<<"Get the value from struct again:"
delete testStructPointer;
// test the constructor
Test testConstructor;
cout<<"Set the value by the construct and get it:"<
return 0;
}
第三,struct可以有析构函数么?让我来验证一下;
[cpp]
#include "stdafx.h"
struct Test
{
int a;
Test()
{
a = 100;
}
int getA()
{
return a;
}
void setA(int temp)
{
a = temp;
}
~Test()
{
cout<<"Destructor function called."<
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test testStruct;
testStruct.setA(10);
cout<<"Get the value from struct:"<setA(20);
cout<<"Get the value from struct again:"
delete testStructPointer;
// test the constructor
Test testConstructor;
cout<<"Set the value by the construct and get it:"<
return 0;
}
是的,完全支持析构函数。
第四,struct支持继承么?再让我写代码验证一下;
[cpp]
#include "stdafx.h"
struct A
{
int a;
A()
{
a = 10;
}
void print()
{
cout<<"I am from A"<
}
};
struct B : A
{
int b;
B()
{
a = 30; // set a to 30
b = 20;
}
/*void print()
{
cout<<"I am from B"<
}*/
};
int _tmain(int argc, _TCHAR* argv[])
{
B b1;
cout<
cout<
b1.print();
A a1;
cout<
a1.print();
return 0;
}
运行上述代码,struct支持继承。
第五,struct支持多肽么?写代码测试一下便知;
[cpp]
#include "stdafx.h"
struct A
{
virtual void print() = 0;
};
struct B : A
{
void print()
{
cout<<"I am from B"<
}
};
struct C : A
{
void print()
{
cout<<"I am from C"<print(); // call B, not A
a1 = c1;
a1->print(); // call C, not A
return 0;
}
第六,struct支持private、protected和public关键字么?
[cpp]
#include "stdafx.h"
struct A
{
private:
int b;
protected:
int c;
public:
A()
{
b = 10;
c = 20;
d = 30;
}
int d;
};
struct B : A