对象的声明,类的构造函数和拷贝构造函数何时调用

本文详细介绍了C++中类的构造过程,包括普通构造函数和拷贝构造函数的使用方式。通过具体的示例代码展示了如何定义和使用这些构造函数,并解释了它们在对象创建过程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

\

class Point
{
public:
Point(int x=0,int y=0 );
Point(Point&);
virtual ~Point();
int x,y;

};
// Point.cpp: implementation of the Point class.
//
//////////////////////////////////////////////////////////////////////

#include "Point.h"
#include <stdio.h>
#include <iostream>
using namespace std;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Point::Point(int x,int y)
{
this->x = x;
this->y = y;
cout<<"构造函数被调用"<<endl;
}
Point::Point(Point& p)
{
this->x = p.x;
this->y = p.y;
cout<<"拷贝构造函数被调用"<<endl;
}

Point::~Point()
{

}

class Test
{
public:
Test(int,char*,int,Point);
Test(Test&);
virtual ~Test();

void setPoint(Point);
private:
Point p1;
const int a;
int id;
char* name;
static int count;

};

Test::Test(int id,char* name,int a,Point p):a(a) //
{
//到这里,会调用Point的构造函数,p1会先声明
this->p1 = p;
this->id = id;
this->name = new char[strlen(name)+1]; //Ï
if(this->name!=0)
strcpy(this->name,name);
}
Test::Test(Test& t):a(t.a)
//到这里,会调用Point的构造函数,p1会先声明
p1 = t.p1;
id = t.id;
name = new char[strlen(t.name)+1];
if(name!=0)
strcpy(name,t.name);
cout<<"test"<<endl;
}
Test::~Test()
{

}
int Test::count = 10;

void Test::setPoint(Point p)
{

//在这里拷贝构造函数被调用,因为p1已经被声明过了

this->p1 = p;
}

void main()
{
cout<<"*********************"<<endl;
Point pp(1,1); //构造函数被调用
Point pp2; //构造函数被调用,而且必须有默认构造函数,可以使用无参数初始化,Point(int x=0,int y=0)或者Point()
cout<<"8888888"<<endl;
pp2 = pp; //不再调用
Point pp3 = pp; //拷贝函数被调用

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值