目录
在GNU C++标准库的源码中有大量的struct的应用,其用法看着跟class基本一样,显然C++对C中的struct做了扩展,这两者之间有啥区别了?
struct一样支持访问控制,构造函数,析构函数,列表初始化语法,静态成员,内联函数,友元函数等,class支持的功能都可以用到struct上,两者最大的区别是struct的默认访问权限是public,而class默认是private。
#include <iostream>
using std::cout;
struct A{
//默认是public
int a=1;
static int b;
A(int i):a(i){cout<<"construct A\n";};
~A(){cout<<"destroy A\n";};
void show();
private:
int c=2;
friend void showC(A & a);
};
void A::show(){
cout<<"struct A,a="<<a<<"\n";
}
void showC(A & a){
cout<<"struct A,c="<<a.c<<"\n";
}
int A::b=2;
int main(){
A a(3);
cout<<"a="<<a.a<<",b="<<A::b<<"\n";
a.show();
showC(a);
return 0;
}
struct一样支持多态,单继承,多继承,公有/私有/保护继承,同class的区别是,struct默认是公有继承,而class默认是私有继承,如下示例:
#include <iostream>
using std::cout;
struct A{
virtual ~A(){};
virtual void show(){cout<<"show A\n";};
};
struct B:A{
void show(){cout<<"show B\n";};
};
struct C{
void showC(){cout<<"show C\n";};
};
struct D:private B,C{
void showD(){cout<<"show D\n";};
};
int main(){
B b;
A * a=&b;
a->show();
D d;
d.showC();
d.showD();
B * d2=(B*)&d;
d2->show();
return 0;
}
struct同class一样可以定义模板,可以作为模板参数,注意模板定义中可以用typename代替class,但不能用struct代替class,如下示例:
#include <iostream>
#include <string>
#define TEMP template <class T1, class T2,int typeNum>
TEMP
struct Pair
{
private:
T1 a;
T2 b;
int type=typeNum;
public:
T1 & first();
T2 & second();
T1 first() const { return a; }
T2 second() const { return b; }
int getType() const { return type; }
Pair(const T1 & aval, const T2 & bval) : a(aval), b(bval) { }
Pair() {}
};
TEMP
T1 & Pair<T1,T2,typeNum>::first()
{
return a;
}
TEMP
T2 & Pair<T1,T2,typeNum>::second()
{
return b;
}
struct A{
int getA(){return 3;};
};
int main()
{
Pair<int ,std::string,11> a(1,"test");
std::cout<<"first:"<<a.first()<<",second:"<<a.second()<<",type:"<<a.getType()<<"\n";
Pair<A,std::string,12> b(A(),"test2");
std::cout<<"first:"<<b.first().getA() <<",second:"<<b.second()<<",type:"<<b.getType()<<"\n";
return 0;
}