书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

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;
}

 

posted on 2012-04-19 20:29  More study needed.  阅读(231)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!