C++基础:

什么是多态:(哑巴了吧,你知道你倒是说呀),所谓多态也就是一个接口的多种实现方式。

多态包括:虚函数,纯虚函数,覆盖,模板(重载与多态没有关系)

虚函数:虚函数是带有virtual关键字的函数,定义一个函数为虚函数,定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。纯虚函数是 类似 virtual void hanShu(int B)=0;这样的函数。带有纯虚函数的类是抽象类,必须实例化纯虚函数后才能进行对象的生成。C++的虚函数主要作用是“运行时多态”

构造函数析构函数在继承类时候的调用关系是:

先基类构造然后派生类构造,先派生类析构再基类析构。你继承你爹的财产不得礼让一点儿,先满足他老人家的需求再满足自己的需求啊,有什么事儿的时候不得自己先担着然后让你爹站你后面啊!

  1. char*p="hello" ; //一个指针,指向只读数据块(section)里的 "hello ",可被编译器放入字符串池(也就是说, 你在写一个char *q= "hello ",可能和p共享数据)
  2. const char*q="hello"
  3. int a[]="tsinghua" //一个数组,分配在可写数据块(section),不会被放到字符串池中
  4. 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的函数输出了。

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值