/*
**test22.cpp : Defines the entry point for the console application.
**系统winXP SP3 32位.
**struct与class的异同、赋值、作用域
*/
#include "stdafx.h"
#include "iostream.h"
struct SA{
public:
const char* GetName() const;
private:
char* sa_name;
int sa_height;
int sa_weight;
};
class CA{
public:
const char* GetName() const;
private:
//CA_2 ca_2; //这里这样写是错误的,因为此时编译器并不知道CA_2的具体大小,不能为其分配适应的内存空间
char* ca_name;
int ca_height;
int ca_weight;
};
class CA_2{
public:
const char* GetName() const;
private:
CA ca;
char* ca_2_name;
int ca_2_height;
int ca_2_weight;
};
int main(int argc, char* argv[])
{
SA sa;
CA ca1;
CA ca2 = ca1; //可以进行直接的赋值操作
CA_2 ca_2;
cout<<sizeof(sa)<<endl; //12,char*类型与int一样,都占有4个字节,故一共12个字节
cout<<sizeof(ca1)<<endl; //12
cout<<sizeof(ca2)<<endl; //12
cout<<sizeof(ca_2)<<endl; //24
return 0;
}
Tips1:c/c++中struct的默认访问权限是public,而class则是private,struct与class除了这默认访问权限的不同外没有任何区别,在c++中,如果你声明了每个成员(函数与变量)的访问权限,那么用struct或者class关键字是相同的(如上例SA与CA是完全相同的)。
Tips2:c/c++中支持相同对象类型之间的赋值操作,但不能直接判断大小与是否相等。这是因为相同数据类型内部的