c++语法3

2018-02-04  本文已影响12人  yangzai

上篇继续学习多态、类型转换

多态:

多态(Polymorphism)按字面的意思就是“多种状态”。在面向对象语言中,接口的多种不同的实现方式即为多态
我们这里使用的模型是:人,英国人,中国人,都有吃饭的方法,人用手吃饭,英国人用刀叉,而中国人用筷子。我们问“这个人怎么吃饭的?”,应该根据其国别来回答,而不是简单地说“用手吃”。这就是多态。
在c++中多态是使用虚函数来实现的:

#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
private:
    int a;
public:
      //定义虚函数
    virtual void eating(void) { cout<<"use hand to eat"<<endl; }
};
class Englishman : public Human {
public:
        //重写虚函数
    void eating(void) { cout<<"use knife to eat"<<endl; }
};
class Chinese : public Human {
public:
    void eating(void) { cout<<"use chopsticks to eat"<<endl; }
};
//实现虚函数
void test_eating(Human& h){
    h.eating();
}
int main(int argc, char **argv){
    Human h;
    Englishman e;
    Chinese c;
    test_eating(h);
    test_eating(e);
    test_eating(c);
    cout<<"sizeof(Human) = "<<sizeof(h)<<endl;
    cout<<"sizeof(Englishman) = "<<sizeof(e)<<endl;
    cout<<"sizeof(Chinese) = "<<sizeof(c)<<endl;
    return 0;
}

输出:

use hand to eat
use knife to eat
use chopsticks to eat

原理:
对于虚函数,采用动态联编:有虚函数的对象里有一个指针,指向虚函数表;
调用虚函数时,会根据对象里的指针找到表,从表中取出函数来执行
对于非虚函数,采用静态联编:编译时就确定调用哪个函数
差别:静态联编效率高,动态联编支持多态
除此之外,多态的使用也是有条件的:

test_func(Human* h):
test_func(Human& h):使用指针或引用来使用对象时,才有多态
test_func(Human h):传值时,无多态
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
private:
    int a;
public:
    virtual void eating(void) { cout<<"use hand to eat"<<endl; }
      //析构函数是虚函数
    virtual ~Human() { cout<<"~Human()"<<endl; }
      //返回值是引用或指针时可以使用虚函数
    virtual Human* test(void) {cout<<"Human's test"<<endl; return this; }
};
class Englishman : public Human {
public:
    void eating(void) { cout<<"use knife to eat"<<endl; }
    virtual ~Englishman() { cout<<"~Englishman()"<<endl; }
    virtual Englishman* test(void) {cout<<"Englishman's test"<<endl; return this; }
};
class Chinese : public Human {
public:
    void eating(void) { cout<<"use chopsticks to eat"<<endl; }
    virtual ~Chinese() { cout<<"~Chinese()"<<endl; }
    virtual Chinese* test(void) {cout<<"Chinese's test"<<endl; return this; }
};
void test_eating(Human& h){
    h.eating();
}
void test_return(Human& h){
    h.test();
}
int main(int argc, char **argv){
    Human h;
    Englishman e;
    Chinese c;
    test_return(h);
    test_return(e);
    test_return(c);
    return 0;
}
类型转换

c中隐式类型转换是由编译器执行的:

#include <stdio.h>
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  // doubleתΪint
    char *str = "100ask.taobao.com";
    int *p = str; // char *תΪint * 
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, str, p);
    return 0;
}

c中显示类型转换用()实现:

#include <stdio.h>
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  
    char *str = "100ask.taobao.com";
    int *p = (int *)str;
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, (unsigned int)str, (unsigned int)p);
    return 0;
}

c++中使用reinterpret_cast()来实现转换:

#include <stdio.h>
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  
    char *str = "100ask.taobao.com";
    int *p = reinterpret_cast<int *>(str); 
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, reinterpret_cast<unsigned int>(str), reinterpret_cast<unsigned int>(p));
    return 0;
}

reinterpret_cast相当于C中的小括号的类型转换。但是它不能转换带const的。
可以使用const_cast()去掉const属性再转换:

#include <stdio.h>
int main(int argc, char **argv){
    double d = 100.1;
    int i = d;  
    const char *str = "100ask.taobao.com";
    char *str2 = const_cast<char *>(str);
    int *p = reinterpret_cast<int *>(str2);
    printf("i = %d, str = 0x%x, p = 0x%x\n", i, reinterpret_cast<unsigned int>(str), reinterpret_cast<unsigned int>(p));
    return 0;
}

除此之外,C++还提供动态转换dynamic_cast(),但是只能用于含有虚函数类里面,因为它需要查找虚函数表来确定类的信息:

#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
private:
    int a;
public:
    virtual void eating(void) { cout<<"use hand to eat"<<endl; }
    virtual ~Human() { cout<<"~Human()"<<endl; }
    virtual Human* test(void) {cout<<"Human's test"<<endl; return this; }
};
class Englishman : public Human {
public:
    void eating(void) { cout<<"use knife to eat"<<endl; }
    virtual ~Englishman() { cout<<"~Englishman()"<<endl; }
    virtual Englishman* test(void) {cout<<"Englishman's test"<<endl; return this; }
};
class Chinese : public Human {
public:
    void eating(void) { cout<<"use chopsticks to eat"<<endl; }
    virtual ~Chinese() { cout<<"~Chinese()"<<endl; }
    virtual Chinese* test(void) {cout<<"Chinese's test"<<endl; return this; }
};
void test_eating(Human& h){
    Englishman *pe;
    Chinese    *pc;
    h.eating();
    /* 想分辨这个"人"是英国人还是中国人? */
    if (pe = dynamic_cast<Englishman *>(&h))
        cout<<"This human is Englishman"<<endl;
    if (pc = dynamic_cast<Chinese *>(&h))
        cout<<"This human is Chinese"<<endl;
}
int main(int argc, char **argv){
    Human h;
    Englishman e;
    Chinese c;
    test_eating(h);
    test_eating(e);
    test_eating(c);
    return 0;
}

输出:

use hand to eat
use knife to eat
use chopsticks to eat
use hand to eat
use knife to eat
This human is Englishman
use chopsticks to eat
This human is Chinese
~Chinese()
~Human()
~Englishman()
~Human()
~Human()

这样我们就能再运行时确定多态的具体类型。
动态转换的格式:dynamic_cast < type-id > ( expression )
把expression转换成type-id类型的对象。
Type-id必须是类的指针、类的引用或者void *;
如果type-id是类指针类型,那么expression也必须是一个指针;
如果type-id是一个引用,那么expression也必须是一个引用。

动态类型是运行是转换,如果想在编译时转换可以使用格式:static_cast():

int main(int argc, char **argv){
    Human h;
    Guangximan g;
    Englishman *pe;
    //下行转换是可以的但不安全
    pe = static_cast<Englishman *>(&h);
    //上行转换,但是不能转换成无关的Englishman类型,在编译时就报错,只能转换成相关的Chinese人
    Chinese *pc = static_cast<Chinese *>(&g);
    return 0;
}

总结下静态转换:

  1. 用于类层次结构中基类和子类之间指针或引用的转换。
  2. 进行上行转换(把子类的指针或引用转换成基类表示)是安全的;
  3. 进行下行转换(把基类指针或引用转换成子类指针或引用)时,由于没有动态类型检查,所以是不安全的。
上一篇下一篇

猜你喜欢

热点阅读