typedef struct _Point3d
{
float x;
float y;
float z;
} Point3d;
|
void Point3d_print( const Point3d* pd )
{
printf("(%g, %g, %g)", pd->x,
pd->y,
pd->z
);
}
//
%g和%G是实数的输出格式符号。
它是自动选择%f和%e两种格式中较短的格式输出,并且不输出数字后面没有意义的零。
|
class Point
{
public:
Point( float x = 0.0 ) : _x(x) {}
float x() { return _x; }
void x( float val ) { _x = val; }
// ...
protected:
float _x;
};
class Point2d : public Point
{
public:
Point2d( float x = 0.0, float y = 0.0 ) : Point( x ), _y( y ) {}
// ...
protected:
float _y;
}
class Point3d : public Point2d
{
public:
Point3d( float x = 0.0, float y = 0.0, float z = 0.0 ) : Point2d( x, y ), _z( z ) {}
// ...
protected:
float _z;
}
|
2种成员变量(class data members):静态的(static) 和 非静态的(non-static);
3种成员函数(class member functions):静态的、非静态的 和 虚拟的(virtual)。
|
class Point
{
public:
Point( float valx );
virtual ~Point();
float x() const;
static int PointCount();
protected:
virtual ostream& print( ostream &os ) const;
float _x;
static int _point_count;
};
|
class Base
{
public:
Base();
~Base();
};
// sizeof(Base) = ?
|
class Base
{
public:
Base();
~Base();
protected:
double m_Double;
int m_Int;
char m_BaseName;
};
// sizeof(Base) = ?
|
第一题: 答案是1。
class Base 里只有构造函数和析构函数,由前面的内容所知,class 的 member functions 并不存放在 class 以及其实例内,因此,sizeof(Base) =
1。是的,结构不是0,而是1,原因是因为,class 的不同实例,在内存中的地址各不相同,一个字节只是作为占位符,用来给不同的实例分配不同的内存地址的。
第二题:答案是16。
double 类型的变量占用
8个字节,int 占了4个字节,char 只占一个字节,但这里它会按 int 进行对齐,Base 内部会填补3个字节的内存大小。最后的大小就是 8 + 4 + 1 + 3 = 16。
大家可以调整三个成员变量的位置,看看结果会有什么不同。
|
Base* p_Base;
int* p_Int;
vector |