欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

继承的构造函数

程序员文章站 2022-05-14 09:58:14
...

1.单继承

#include"iostream"
using namespace std;

class Base {
public:
	int b;
	Base() { b=1; };
	Base(int b_) { b = b_; };
};

class Derive :public Base {
public:
	int d{0};
	Derive(int b_) :Base(b_){}	//没有这句Derive d(2)会报错
	Derive() = default;			//自动调用Base()构造b
};

int main() {
	Derive d1;
	Derive d2(2);
	cout << d1.b << endl;
	cout << d2.b << endl;
	
	return 0;
}

为什么继承构造函数需要using:https://www.runoob.com/w3cnote/cpp11-inheritance-constructor.html

2.多继承

#include<iostream>
using namespace std;

struct Base1
{
	Base1() = default;
	Base1(const string& s_) { s = s_; cout << "Base1" << endl; };
	string s;
};

struct Base2
{
	Base2() = default;
	Base2(const string& s_) { s = s_; cout << "Base2" << endl;
	};
	string s;
};

struct D1 :Base1, Base2 {
	//using Base1::Base1;
	//using Base2::Base2;	会有相同函数冲突
	D1(const string& s) :Base1(s), Base2(s) { cout << "D1" << endl; };
	D1() = default;
};

int main() {
	D1 d("hello");
	cout << d.Base1::s;
	return 0;
}
相关标签: c++