C++ 构造函数各种怪式一网打尽

1.正常无参(无初始值)

View Code
#include "iostream"

#include "string"

using namespace std;



class Point

{

public:

    Point()

    {

        cout<<"Default constructor called."<<endl;

        cout<<x<<" "<<y<<endl;

    }

private:

    int x, y;



};

int main()

{

    Point *ptr1=new Point();

    delete ptr1;

}

 

2.正常有参

View Code
#include "iostream"

#include "string"

using namespace std;



class Point

{

public:

    Point(int x, int y)

    {

        cout<<"Default constructor called."<<endl;

        cout<<x<<" "<<y<<endl;

    }

private:

    int x, y;



};

int main()

{

    Point *ptr1=new Point(1, 2);

    delete ptr1;

}

 

3.不正常无参(有初始值)

View Code
#include "iostream"

#include "string"

using namespace std;



class Point

{

public:

    Point():x(0),y(0)

    {

        cout<<"Default constructor called."<<endl;

        cout<<x<<" "<<y<<endl;

    }

private:

    int x, y;



};

int main()

{

    Point *ptr1=new Point();

    delete ptr1;

}

 

4.不正常有参

View Code
#include "iostream"

#include "string"

using namespace std;



class Point

{

public:

    Point(int x, int y):x(x),y(y)

    {

        cout<<"Default constructor called."<<endl;

        cout<<x<<" "<<y<<endl;

    }

private:

    int x, y;



};

int main()

{

    Point *ptr1=new Point(1, 2);

    delete ptr1;

}

 

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