0
点赞
收藏
分享

微信扫一扫

C++菱形继承如何调用基类对象

dsysama 2022-03-19 阅读 54
c++
#include <iostream>
using namespace std;

//派生类对象中的基类成员,

class A {
protected:
	int n;
public:
	A(int n):n(n){}
	friend class B;
};

class B :public A {
	int n;
public:
	B(int n1,int n2):n(n1),A(n2){}

	void show(A* a) {
		printf("a->n: %d\n", a->n);	//参数传递进来的基类对象成员
		printf("this->A::n:%d\n", this->A::n);//派生类对象中包含的基类对象成员
		printf("this->n:%d\n", this->n);//派生类对象成员
	}
};
int main(int argc, const char* argv[]) {

	A a(11);

	B b(22, 444);
	b.show(&a);



	while (1);
	return 0;
}

#include <iostream>
using namespace std;

struct A {
	int n;
	A() { cout << "A类无参构造" << endl; }
	A(int n) :n(n) { cout << "A类构造" << endl; }
	~A() { cout << "A类析构" << endl; };
};

struct B :public A {
	int n;
	B() { cout << "B类无参构造" << endl; }
	B(int n, int n1) :n(n), A(n1) { cout << "B类构造" << endl; }
	~B() { cout << "B类析构" << endl; }
};

struct C :public A {
	int n;
	C() { cout << "C类无参构造" << endl; }
	C(int n, int n1) :n(n), A(n1) { cout << "C类构造" << endl; }
	~C() { cout << "C类析构" << endl; }
};

struct D :public B, public C {
	int n;
	D() { cout << "D类无参构造" << endl; }
	D(int n, int n1, int n2, int n3, int n4, int n5) :n(n), B(n1, n2), C(n3, n4) {}
};
int main(int argc, const char* argv[]) {

	D d;
	
	while (1);
	return 0;
}
举报

相关推荐

0 条评论