C++中的有参构造函数

C++中的有参构造函数

参数化构造函数:可以将参数传递2给构造函数。通常,这些参封数有助于在创建对象时对其v退货包邮进行初始化。要创建参数化构造函数,只需像添加任何其他函数一样2向其添加参数。当您定义构造函数的主体时,使用参数来初2始化对象。一个类中可以有多个构造函数称为构造函数重载。参数化构造函数的用途:

  • 它用于在创建不同对2象时用不同的值初始化不同对象的各种数据元素。
  • 它用于重载构造函数。

注意:当定义了参数化构造函数并且没有显式2定义默认构造函数时,编译器不会隐式调用默认构造函数。

在参数化构造函数中声明对象时,必须将初始2值作为参数传递给构造函数。对象声明的正常方染发他·好式可能不起作用。可以显式或隐式调用构造函数。2

Example e = Example(0, 50); // Explicit call 显示调用

Example e(0, 50);           // Implicit call 隐式调用

代码示例:

// CPP program to illustrate
// parameterized constructors
#include <iostream>
using namespace std;

class Point {
private:
	int x, y;

public:
	// Parameterized Constructor
	Point(int x1, int y1)
	{
		x = x1;
		y = y1;
	}

	int getX() { return x; }
	int getY() { return y; }
};

int main()
{
	// Constructor called
	Point p1(10, 15);

	// Access values assigned by constructor
	cout << "p1.x = " << p1.getX()
		<< ", p1.y = " << p1.getY();

	return 0;
}

默认的构造函数没有任何参数,但如果需要,构造函数也可 隔阂yr以带有参数。这样在创建对象时就会给对象赋初始值,如下面的例子所示:

#include <iostream>

using namespace std;

class Line
{
    public:
    void setLength( double len );
    double getLength( void );
    Line(double len);  // 这是构造函数

    private:
    double length;
};

// 成员函数定义,包括构造函数
Line::Line( double len)
{
    cout << "Object is being created, length = " << len << endl;
    length = len;
}

void Line::setLength( double len )
{
    length = len;
}

double Line::getLength( void )
{
    return length;
}
// 程序的主函数
int main( )
{
    Line line(10.0);

    // 获取默认设置的长度
    cout << "Length of line : " << line.getLength() <<endl;
    // 再次设置长度
    line.setLength(6.0); 
    cout << "Length of line : " << line.getLength() <<endl;

    return 0;
}

该文章会更新,欢迎大家批评指正。

推荐一个零声学院的C++服务器开发课程,个人觉得老师讲得不错,
分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容
点击立即学习:C/C++后台高级服务器课程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值