📄 staticvirtualinherittest.cpp
字号:
// 这是使用应用程序向导生成的 VC++
// 应用程序项目的主项目文件。
#include <stdafx.h>
#include <iostream.h>
#include <typeinfo.h>
#include <new>
#using <mscorlib.dll>
#include <tchar.h>
#include "son.h"
using namespace System;
char * GetMemory(int num)
{ //返回局部申请的动态空间,可行,
char *p=NULL;
p=new char[num];
return p;
}
int _tmain(void)
{
char *str=NULL;
str = GetMemory(15);
strcpy(str,"hello");
cout<<str<<endl;
delete str;//记得delete
Son son;
Son * pRef=&son;
Father *p1=dynamic_cast<Father *>(pRef);
try
{
//Son *p3 = static_cast<Son *>(p2);
p1->GetName(); //多态!
const char * str = typeid(Son).name();
cout<<str<<endl;//
}
catch(std::bad_exception&)
{
cout<<"cast error:";
}
cout<<p1->GetA()<<endl; //cout 8,数据成员没有多态 ,所以即使p1是指向儿对象的父类指针,
//但Father::GetA()中的m_a是son.Father::m_a,为8,而不是100
cout<<son.m_a<<endl;//100
son.SetA(66,88);
Son s1;
s1=son;//调用=函数,如果函数中没写,则会使得s1与son的父类成员值不同!!!
cout<<"son.Father::m_a and son.m_a is:"<<son.Father::GetA()<<" "<<son.m_a<<endl;
cout<<"s1.Father::m_a and s1.m_a is:"<<s1.Father::GetA()<<" "<<s1.m_a<<endl;//,如果函数中没写=函数,(输出8,88)
Son s2=s1;//调用拷贝构造函数,如果函数中的冒号后没写Father(son)
//则强行调Father(),会使得s2与s1得父类成员值不同!!!
cout<<"s2.Father::m_a is:"<<s2.Father::GetA()<<"and s1.Father::m_a is:"<<s2.Father::GetA()<<endl;//66,66
cout<<s2.m_a<<endl; //cout 88
//测试隐藏func():子类写了一个void func(float count),将父类的所有的func()隐藏!!
// s2.func("gao");//报错:error C2664: “Son::func” : 不能将参数 1 从“char [4]”转换为“float”
//原因即: 由于子类隐藏了父类的func(char *p)函数,则子类没有了void func(char *p)!!
s2.func(5); //由于子类隐藏了父类的func(int count)函数,则子类没有了void func(int count),
//只会将5转为5.0f,调用自己的func(float count);所以cout father func(int count)
//并不是子类没有或着没办法调func(char *p),其实子类有这个函数,用下面的写法
s2.Father::func("gao");//即隐藏的函数当然要显示调用,否则叫什么隐藏?
Father &fp1=s2;
fp1.func(5.6);//截断5.6为5 ,调用father::func(int count)!,
//总之,不具备多态时,"想"父类的数据成员或函数时,要显示调用!自己没有那样的函数时,报错!
//测试”间接多态“,即转到父类成员函数中,又在函数中碰到virtual 函数!
fp1.test1();//间接多态,调用了Father::test1(),进入后,碰到的GetName()是virtual
//则实际是this->GetName(),this是fp1的对象s2的地址,当然多态!注意引用也可多态!
Father *fp2=&son;
fp2->test2(fp1); //间接多态,调用了Father::test1(),进入后,碰到的GetName()是virtual
//则实际是fp1.GetName(),当然多态!
Father fa;
Father *f[2]={&fa,&son};//对象的指针数组,每个成员都是父类型的指针!
for(int i=0;i<2;i++)
{
f[i]->GetName();
}
//cout<<"the f[1]->m_a is:"<<f[1]->m_a;//如果m_a在Father类中是public,正确,注意:实际是son对象的Father::m_a
//所以提示:error C2248: “Father::m_a” : 无法访问 private 成员(在“Father”类中声明)
//很明显,子类的隐藏m_a是public型的,但报错,说明f[1]的权限只能调父类型的成员及函数
//父类型的指针只能调用父类型的成员及函数,但有一个特例--virtual 覆盖函数!
//所以在外面如何想访问子对象的象m_a这样隐藏的成员及
//象func(float count)这样隐藏的成员函数;用父类型的指针无法做到!!!!!!!
cout<<"the f[1]->m_b is:"<<f[1]->m_b;//实际是son对象的Father::m_b没有隐藏
// cout<<"the f[1]->m_d is:"<<f[1]->m_d;//错误!内存截断,没有隐藏更是没法访问!
//提示:error C2039: “m_d” : 不是“Father”的成员
char *q="hao";
int q1=(int)q;
cout<<" the q1'address is "<<q1<<endl;
*(q+1)='m';
cout<<q<<q1<<endl;//q 为hmo
int j=9;
cin>>j;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -