面向对象

对一个空类,默认会产生四个函数: 构造函数 析构函数 拷贝构造函数 和赋值函数。

静态成员变量:

可以在一个类的多个对象间共享数据

静态成员变量需要初始化

如果静态成员变量设为私有的,只能通过静态成员函数来访问。

常成员变量,需要在类初始化列表中初始化 或者加入 static 变成静态的.

class test

{

  const int a = 10;  // wrong

};

class test

{

  static const int a = 10;  // right

};

class test
{
public:
  const int a ;
  test():a(10)     //right
 { 
 }

};

class test
{
public:
  const int a ;
  test():a(10)     //right
 { 
 }

};

构造函数和析构函数 考点:

1. 为什么MFC中析构函数是virtual的?

因为多态, 如下:

Base  * pb = new Child;

delete pb;

如果析构不是virtual,就会直接调用Base的析构,而不是调用Child的析构。

2. 为什么构造又不能是Virtual的?

虚函数是在想调用接口,而又不知道对象具体类型的时候,但是创建对象是一个非常具体的构成,必须要知道具体的类型,所以构造不能为虚。

拷贝构造函数  和赋值函数

String  & operator =(constr String & other)

{

  //判断释放是自己

  if(this ==other)

    return *this;

  //释放原有资源

  if(m_data != null)

  delete m_data;

  //拷贝字符串

  //

  return *this;

}

//其中的const的作用:

1. string s3;

    const string  s4;

    s3= s4;  如果没有const,会报错,因为一些const变量不能转化成非const变量,在编写成员函数的时候也得注意。

2.  s7  s8 s9

     s9 = s7 + s8;  //不加const也会报错 ??

原文地址:https://www.cnblogs.com/herso/p/2081543.html