'init':member function definition looks like a ctor(构造函数的缩写)

具体编译的错误提示如下:
warning C4183: 'init': member function definition looks like a ctor, but name does not match enclosing class
warning C4183: 'method': member function definition looks like a ctor, but name does not match enclosing class
Linking...
main.exe - 0 error(s), 2 warning(s)
意思:成员函数像是一个构造函数ctor,但成员函数的名字又与类名不匹配
/////////////////////////////////////代码如下:
#include<iostream>
using namespace std;
class A
{
public:
 A(){ cout<<"A()"<<endl; init();}
    // ~A(){cout<<"~A()"<<endl;}
     virtual ~A(){cout<<"~A()"<<endl;}
 virtual init(){cout<<"A::init()"<<endl;}
 virtual method(){cout<<"A::method()"<<endl;}
};

class B:public A
{
public:
 B()
 {
  cout<<"B()"<<endl;
 }
 ~B(){cout<<"~B()"<<endl;}
 init(){cout<<"B::init()"<<endl;}
 method(){cout<<"B::method()"<<endl;}
};
int main()
{
 A* p;
 p=new B();
  p->method();
  delete p;//导致内存泄露
  return 0;

//从上面红色字体的成员函数可以看出,函数没有返回类型,也就像是写了一个析构函数,但是却没有和类名相匹配。
正确的代码如下:
#include<iostream>
using namespace std;
class A
{
public:
 A(){ cout<<"A()"<<endl; init();}
    // ~A(){cout<<"~A()"<<endl;}
    virtual  ~A(){cout<<"~A()"<<endl;}
 virtual void init(){cout<<"A::init()"<<endl;}
 virtual void method(){cout<<"A::method()"<<endl;}
};

 

class B:public A
{
public:
 B()
 {
  cout<<"B()"<<endl;
 }
 ~B(){cout<<"~B()"<<endl;}
    void init(){cout<<"B::init()"<<endl;}
 void method(){cout<<"B::method()"<<endl;}
};
int main()
{
 A* p;
 p=new B();
  p->method();
  delete p;//如果不删除对象指针,会导致内存泄露,无法调用析构函数
  return 0;
}
其中温习一个要点:虚析构函数的使用

你可能感兴趣的:(虚函数)