C++中结构体与类到底有什么区别
#include<iostream>
using namespace std;
typedef struct DemoS{
private:
char c;
char x;
int y;
public:
DemoS(){}
DemoS(char c,char x,int y):c(c),x(x),y(y)
{
//cout<<this<<"有参构造"<<endl;
}
inline void setX(char x)
{
this->x=x;
}
inline void printX(){
cout<<this->x<<endl;
}
~DemoS()
{
//cout<<this<<"析构函数"<<endl;
}
private :
char c;
char x;
int y;
public:
DemoC(){}
DemoC(char c,char x,int y):c(c),x(x),y(y)
{
//cout<<this<<"有参构造"<<endl;
}
inline void setX(char x){
this->x=x;
}
inline void printX()
{
cout<<this->x<<endl;
}
~DemoC(){
// cout<<this<<"析构函数"<<endl;
}
};
int main(void)
{
DemoC *c1= new DemoC('a','b',1);
DemoC *c2=c1;
cout<<"c1堆上的地址:"<<c1<<" c2堆上的地址:"<<c2<<endl;
cout<<"c1指针地址:"<<&c1<<" c2指针地址:"<<&c2<<endl;
DemoC c3= DemoC('a','b',1);
DemoC c4=c3;
cout<<"c3:"<<&c3<<" c4:"<<&c4<<endl;
DemoC c5=DemoC('a','b',1);
DemoC *c6=&c5;
cout<<"c5:"<<&c5<<" c6:"<<c6<<endl;
DemoS *s1=new DemoS('a','b',1);
DemoS *s2=s1;
cout<<"s1堆上的地址:"<<s1<<" s2堆上的地址:"<<s2<<endl;
cout<<"s1指针地址:"<<&s1<<" s2指针地址:"<<&s2<<endl;
DemoS s3=DemoS('a','b',1);
DemoS s4=s3;
cout<<"s3:"<<&s3<<" s4:"<<&s4<<endl;
DemoS s5=DemoS('a','b',1);
DemoS *s6=&s5;
using namespace std;
typedef struct DemoS{
private:
char c;
char x;
int y;
public:
DemoS(){}
DemoS(char c,char x,int y):c(c),x(x),y(y)
{
//cout<<this<<"有参构造"<<endl;
}
inline void setX(char x)
{
this->x=x;
}
inline void printX(){
cout<<this->x<<endl;
}
~DemoS()
{
//cout<<this<<"析构函数"<<endl;
}
}DemoS;
private :
char c;
char x;
int y;
public:
DemoC(){}
DemoC(char c,char x,int y):c(c),x(x),y(y)
{
//cout<<this<<"有参构造"<<endl;
}
inline void setX(char x){
this->x=x;
}
inline void printX()
{
cout<<this->x<<endl;
}
~DemoC(){
// cout<<this<<"析构函数"<<endl;
}
};
int main(void)
{
DemoC *c1= new DemoC('a','b',1);
DemoC *c2=c1;
cout<<"c1堆上的地址:"<<c1<<" c2堆上的地址:"<<c2<<endl;
cout<<"c1指针地址:"<<&c1<<" c2指针地址:"<<&c2<<endl;
DemoC c3= DemoC('a','b',1);
DemoC c4=c3;
cout<<"c3:"<<&c3<<" c4:"<<&c4<<endl;
DemoC c5=DemoC('a','b',1);
DemoC *c6=&c5;
cout<<"c5:"<<&c5<<" c6:"<<c6<<endl;
DemoS *s1=new DemoS('a','b',1);
DemoS *s2=s1;
cout<<"s1堆上的地址:"<<s1<<" s2堆上的地址:"<<s2<<endl;
cout<<"s1指针地址:"<<&s1<<" s2指针地址:"<<&s2<<endl;
DemoS s3=DemoS('a','b',1);
DemoS s4=s3;
cout<<"s3:"<<&s3<<" s4:"<<&s4<<endl;
DemoS s5=DemoS('a','b',1);
DemoS *s6=&s5;
cout<<"s5:"<<&s5<<" s6:"<<s6<<endl;
return 0;
}
运行结果:
从上述代码可以看出Struct与Class好像根本没有区别,网上说类是引用类型,结构体是值类型,但是笔者验证了很长时间发现一个问题不管是结构体和类的实例化对象都可以随意存在堆上或者栈上,变量名和指针一定是存在栈上的,但是具体的内容存在堆或者栈就看具体操作,比如int* t=new int(1)这个简单的代码段,因为new返回的地址所以接受它的变量必须也是指针,指针内存地址存在的是栈上的,指向的内存地址是堆上的。而且类也存在着字节对齐的问题,并且Struct也有权限访问的设置(public private protected)和构造函数、析构函数。笔者个人的理解,希望大牛改正,笔者的IDE是codeblocks。