C++学习日志36-----继承与构造、控制访问属性


一、继承与构造

#include<iostream>
using std::cout;
using std::endl;
//任务1:继承构造函数
// 创建基类B及构造函数B(int),B( char)和派生类D; D中不继承/继承B的ctor时的效果
//任务2:派生类中调用基类构造函数
//D中增加成员double x; 及D(double), 在D(double)初始化列表调用B(i)并初始化x
//任务3:派生类先调基类ctor,再构造内嵌对象
// 增加类E及E(int),并再D中加入E的两个对象;创建D对象观察E ctor和B ctor次序

//构造时先调用基类构造函数
class B
{
public:
	B() { cout << "B()" << endl; }
	B(int i) { cout << "B(" << i << ")" << endl; }
	B(char c) { cout << "B(" << c << ")" << endl; }
};
class E
{
public:
	E() { cout << "E()" << endl; }

};
class D :public B {
public:
	using B::B;
	D() = default;
	//D(int i):B(i){}
	//D(char c){}
	D(double x) :e1{}, e2{},B(static_cast<int>(x)){cout << "D" << x << ")" << endl; }
private:
	E e1, e2;
};
int main()
{
	B b;
	D d;
	D d2{ 3.03 };
	std::cin.get();

}

在这里插入图片描述
结果如上图所示。

二、控制访问属性

#include<iostream>
using std::cout;
using std::endl;
class A
{
public:
	int i{ 0 };
protected:
	int j{ 0 };
private:
	int k{ 0 };
};

class Pub :public A
{
public:
	void foo() { i++; j++; }

};

class Pro :protected A
{
public:
	void foo() { i++; j++; }
};

class Pri :private A
{
public:
	void foo()
	{
		i++; j++;
	}
};

int main()
{
	Pub pub;
	Pro pro;
	Pri pri;

	pub.i++; //唯一有效
//	pub.i++; pub.j++; pub.k++;  可取消注释 查看报错
//	pro.i++; pro.j++; pro.k++;
//	pri.i++; pri.j++; pri.k++;

	std::cin.get();

}

protected属性,我的理解是不允许外部访问,但允许子类访问(开小灶)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@白圭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值