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

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

C++ new动态创建对象

View Code

代码就是这样的简单。

无参时的创建。

 

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

代码就是这样的简单。

有参时的创建。

 

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[10];                                                                ;
    delete[] ptr1;
}

这个例子是用来展示用new来创建

对象数组的。

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

导航

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

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