简单来说子类可以直接转换为父类,但是父类如果想转换为子类是有条件的,首先被转换的父类对象起初必须声明为相同的子类对象,也就是说首先是某种子类对象转换来的父类对象可以在转换回去。C#的转换机制比较简单,对于父类、子类没有什么特殊要求,但是C++要求父类必须是含有虚函数的类(实现了多态机制),才能有条件实现父类转为子类。下面用代码说明
C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace inheritCS
{
public class person
{
public string name;
public int age;
}
class student : person
{
public string school;
public int grade;
}
class teacher : person
{
public string subject;
}
class Program
{
static void Main(string[] args)
{
student stu = new student();
stu.name = "pupil";
stu.school = "school1";
stu.grade = 2;
stu.age = 10;
teacher t = new teacher();
t.name = "teacher";
t.age = 30;
t.subject = "maths";
person p1 = stu as person;
if(p1!=null)
{
Console.WriteLine(string.Format("{0} 由 student 转 person 成功", stu.name));
}
else
{
Console.WriteLine(string.Format("{0} 由 student 转 person 失败", stu.name));
}
person p2 = t as person;
if (p2 != null)
{
Console.WriteLine(string.Format("{0} 由 teacher 转 person 成功", t.name));
}
else
{
Console.WriteLine(string.Format("{0} 由 teacher 转 person 失败", t.name));
}
student stuReceiver = p1 as student;
if (stuReceiver != null)
{
Console.WriteLine(string.Format("{0} 由 person 转 student 成功", p1.name));
}
else
{
Console.WriteLine(string.Format("{0} 由 person 转 student 失败", p1.name));
}
stuReceiver = p2 as student;
if (stuReceiver != null)
{
Console.WriteLine(string.Format("{0} 由 person 转 student 成功", p2.name));
}
else
{
Console.WriteLine(string.Format("{0} 由 person 转 student 失败", p2.name));
}
if (Console.ReadKey(true).Key == ConsoleKey.Enter)
{
return;
}
}
}
}
执行结果如下图。这里person是父类,student、teacher是子类,student、teacher转person完全没问题,student转化为的父类对象可以成功转换回student,但是teacher转化为的父类对象无法转换为student
C++代码
// inheritCPP.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
class person
{
public:
char name[10];
int age;
virtual void Show() { printf("This is Base calss"); }
};
class student :public person
{
public:
char school[10];
int grade;
};
class teacher :public person
{
public:
char subject[10];
};
int main()
{
student stu;
strcpy_s(stu.name, "pupil");
strcpy_s(stu.school, "school1");
stu.grade = 2;
stu.age = 10;
teacher t;
strcpy_s(t.name, "teacher");
t.age = 30;
strcpy_s(t.subject, "maths");
person* p1 = NULL;
person* p2 = NULL;
student* stuReceiver;
if ((p1 = &stu) != NULL)
{
printf("%s 由 student 转 person 成功\n", stu.name);
}
else
{
printf("%s 由 student 转 person 失败\n", stu.name);
}
if ((p2 = &t) != NULL)
{
printf("%s 由 teacher 转 person 成功\n", t.name);
}
else
{
printf("%s 由 teacher 转 person 失败\n", t.name);
}
if (stuReceiver = dynamic_cast<student*>(p1))
{
printf("%s 由 person 转 student 成功\n",p1->name);
}
else
{
printf("%s 由 person 转 student 失败\n", p1->name);
}
if (stuReceiver = dynamic_cast<student*>(p2))
{
printf("%s 由 person 转 student 成功\n", p2->name);
}
else
{
printf("%s 由 person 转 student 失败\n", p2->name);
}
getchar();
return 0;
}
整体思路和C#一样,但是实现时父类必须含有虚函数已实现多态机制,这样才能实现有条件的父类转换为子类,执行结果如下图