c++中调用基类的构造函数对基类的私有成员初始化

本文探讨了如何在C++派生类的构造函数中调用基类的构造函数来初始化基类的私有成员。通过示例代码展示了基类的复制构造函数在派生类中的应用,解释了在不同场景下如何正确地初始化基类的私有属性。
摘要由CSDN通过智能技术生成

如果基类有私有成员,并且需要在派生类中的构造函数中初始化。这是会用到基类的复制构造函数。

有如下示例:


#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class base{
private:
	int i;
public:
	base() :i(0)
	{
		cout << "base constructer.i = "<< i << endl;
	}
	base(int n) :i(n)
	{
		cout << "base(n) constructer.i = " << i << endl;
	}
	base(const base &n) :i(n.i)
	{
		cout << "base&n constructer.i = " << i << endl;
	}
};
class test : public base{
private:
	int j;
public:
	test() :base(0), j(0) { cout << "test constructer .j = " << j << endl; }
	test(int i, int j) :base(i), j(j) { cout << "test(i,j) constructer .j = " << j << endl; }
	test(const test &obj) :base(obj), j(obj.j) { cout << "test(const test&obj) constructer .j = " <<
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值