什么是多态:(哑巴了吧,你知道你倒是说呀),所谓多态也就是一个接口的多种实现方式。
多态包括:虚函数,纯虚函数,覆盖,模板(重载与多态没有关系)
虚函数:虚函数是带有virtual关键字的函数,定义一个函数为虚函数,定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。纯虚函数是 类似 virtual void hanShu(int B)=0;这样的函数。带有纯虚函数的类是抽象类,必须实例化纯虚函数后才能进行对象的生成。C++的虚函数主要作用是“运行时多态”
构造函数析构函数在继承类时候的调用关系是:
先基类构造然后派生类构造,先派生类析构再基类析构。你继承你爹的财产不得礼让一点儿,先满足他老人家的需求再满足自己的需求啊,有什么事儿的时候不得自己先担着然后让你爹站你后面啊!
- char*p="hello" ; //一个指针,指向只读数据块(section)里的 "hello ",可被编译器放入字符串池(也就是说, 你在写一个char *q= "hello ",可能和p共享数据)
- const char*q="hello"
- int a[]="tsinghua" //一个数组,分配在可写数据块(section),不会被放到字符串池中
- const int b[]="tsinghua"
p是等于q的,因为指针是个类型,好比 int 类型;a!=b,因为a 和b其实是两段内存的初始地址
#pragma once
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
virtual void print()
{
cout << " this is A" << endl;
}
};
class B:public A
{
public:
virtual void print()
{
cout << "this is B" << endl;
}
};
class MyString
{
//默认是private类型 struct 默认是public类型;
public:
char* str;
public:
MyString(const char* str1=NULL)
{
if (str1 == NULL)
str = NULL;
else
{
str = new char[strlen(str1)+1];
strcpy_s(str,strlen(str1)+1, str1);
}
}
~MyString();
MyString operator=(const MyString& mstr);
};
MyString::~MyString()
{
delete[]this->str;
}
MyString MyString::operator=(const MyString&mystr)
{
//面得把自己赋值给自己出错
if (this != &mystr)
{
delete[]this->str;
this->str = NULL;
if (mystr.str != NULL)
{
this->str = new char[strlen(mystr.str)];
strcpy_s(str, strlen(mystr.str), mystr.str);
}
}
return *this;
}
int main()
{
A* ptr_a = new A();
ptr_a->print();
A* ptr_b = new B();
ptr_b->print();
MyString ms=MyString("hello my_string");
cout << ms.str << endl;
getchar();
return 0;
}
这个输出铁定的是A函数的俩输出,但是加上virtual 关键字第二个就变成B的函数输出了。