Conversion between base class pointer and derived class pointer


1. Directly use the base class pointer to refer to the base class object
. 2. Directly use the derived class pointer to refer to the derived class object
. 3. Use the base class pointer to refer to a derived class object. Since the derived class object is also an object of the base class, this reference is safe. ,
but only base class members can be referenced. The compiler will report a syntax error if you try to refer to members that are only found in derived classes through a base class pointer. (The answer to this problem is virtual functions and polymorphism)
4. Use the derived class pointer to refer to the object of the base class. This way of quoting will result in a syntax error. The derived class pointer must first be cast to the base class pointer, this method is safe.

In Hou Jie's introduction to the simple things in MFC, Chapter 2 C++ Important Properties:
1. If you use a "pointer of the base class" to point to an "object of the derived class", then you can only call the definition of the base class through the pointer 2. If you use a "pointer of a derived class" to point to an " object
of a base class", you must first do an explicit cast, which is dangerous.
3. If both the base class and the derived class define a "function with the same name", then when calling a member function through an object pointer, which function is called must depend on the original type of the pointer, not what the pointer actually points to. It depends on the type of the object, which is similar to the meaning of point 1.

#include <iostream>
#include <stdlib.h>

using namespace std;

class A
{
public:
char str[20];
void f(){cout<<"class A"<<endl;}
void fff(){cout<<"class A's str "<<str<<endl;}void add(){cout<<"class A address: "<<this<<endl;}}; 

class B:public A
{
public:
int i;
char sb[20];
B(){cout<<"class B constructor is run."<<endl;}
~B(){cout<<"class B destructor is run."<<endl;}
void f(){cout<<"class B"<<endl;}
void ff(){cout<<"class B "<<i<<str<<sb<<endl;}
void add(){cout<<"class B address: "<<this<<endl;}
};

int main(int argc, char *argv[])
{
//声明父类对象 
A b;
//声明父类对象的指针,指向父类对象 
A *pa=&b;
pa->add();
//这个写法正确,不过很危险,因为pa到底是指向B还是A是不确定的.如果能明确的知道
//pa是指向B类对象的,就如现在写的这个,那么没问题,如果pa指向A类对象,就会存在
//风险.改变指针的类型,并不会影响内存分配既不会调用构造函数

B *pb=(B *)pa;
//类型强制转化后,指向的地址相同. 但会按转化类型访问数据成员.
//成员函数属于类而不属于对象.各对象共用类的成员函数.强制转换成 B 类型后,可
//调用类的成员函数。编译pb->add();后的代码只是调用add函数的时候传入了pb的对
//象指针this
pb->add();

//由于pa指向的是父类对象的地址,这个指针被强制转换为派生类指针后,会出现内存越
//界访问的情况,是不安全的. 
pb->i=100;
char dsd[100];
strcpy(pb->sb, " class B's sb.");
strcpy(pb->str, " class A's str.");

//pb->f()调用的具体函数,视指针的原始类型而定,而不是视指针实际所指的对象的
//类型而定.如果是虚函数,则视实际所指的对象的类型而定 
pb->f();
pb->ff();
pb->fff();

system("PAUSE"); 
return 0;
}

附上连接:转载请标明出处:

http://ltiger.blog.sohu.com/40050539.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325591533&siteId=291194637