结构体继承自结构体

C++ Code:

/*
	功能:结构体继承自结构体

	结论:
		1. 结构体可以继承自结构体
		2. 结构体同样有构造函数和析构函数
*/

#include <iostream>

using namespace std;

struct MNode
{
	int val;
	MNode()
	{
		val = 10;
		cout<<"MNode(): "<<val<<endl;
	}
	~MNode()
	{
		val = 20;
		cout<<"~MNode(): "<<val<<endl;
	}
};

struct MList: public MNode
{
	char name[10];
	MList()
	{
		strcpy(name, "World");
		cout<<"MList(): val="<<val<<", name="<<name<<endl;
	}
	~MList()
	{
		strcpy(name, "World2");
		cout<<"~MList(): val = "<<val<<", name = "<<name<<endl;
	}
	void display()
	{
		cout<<"MList::display(): val="<<val<<", name="<<name<<endl<<endl;
	}
};

int main()
{
	MList a;
	a.display();

	strcpy(a.name, "Hello");
	a.val = 100;
	a.display();

	return 0;
}


运行结果:

C:\Documents and Settings\liujiangtao\桌面\te\Debug>m.exe
MNode(): 10
MList(): val=10, name=World
MList::display(): val=10, name=World

MList::display(): val=100, name=Hello

~MList(): val = 100, name = World2
~MNode(): 20


 

你可能感兴趣的:(c,struct)