C++中的类型转换关键字及其用法

类型转换
C语言中的类型转换过于粗暴,难于定位
在C++中用一下四个关键字进行类型转换,方便定位
1.static_cast<T/*需要转换成的类型*/>(表达式)
用于基本数据类型之间的转换,如int ,char,float,double等
int x=106;
char y='c';
y=static_cast <char>(x);
这样x就被转换成char类型了;


也用于有继承关系之间的类的转换,类指针也可以
又如:
class A{};
class B:public A{};
A a;
B b;
a=static_cast<A>(b);
A *pa;
B *pb;
pb=static_cast<B*>(pa);
2.reinterpret_cast<T>();
用于指针类型之间的转换;
3.const_cast<T>();
用于去掉const修饰的常变量的const属性;
const int a=1;声明一个常量的名字为a,在下面出现的a都会


用1替代
int *p=&a;//会报错
int *p=<int *>&a;//不会报错
const int &b=1;//
int &c=const_cast <int &>(b);//
int &c=const_cast <int &>(b);
#include<iostream>
using namespace std;
int main()
{
	const int &b=1;
	cout<<"b="<<b<<endl;
	cout<<&b<<endl;
	int &c=const_cast<int &>(b);
	c=5;
	cout<<"c="<<c<<endl;
	cout<<&c<<endl;
	return 0;
}


结果为:
b=1;
c=5;
证明在定义一个常引用时也会给他分配空间,可以通过类型转换关键字const_cast改变常量的属性,再通过转换后的变量名来修改此常变量的值
dynamic_cast
主要用于类层次之间的转换,还可以用于类之间的交叉转换,具有类型转换功能

但是一定要有多态才行,子转父可以,父转子不行,因为在子类中不经继承了父类的多有成员变量而且自己本身还定义了新的成员变量,父赋值给子的时候子类后定义出来的成员变量没得赋值,这需要用到虚表查看类的信息,所以要有虚函数。

#include <iostream>
using namespace std;
class A
{
  public:
    int m_a;
    A()
    {
        m_a = 10;
    }
    virtual void  show()
    {
        cout <<"dasdfa"<< endl;
    }
};
class B :  public A
{
  public:
    int m_b;
    B()
    {
        m_a = 100;
        m_b = 200;
    }
    void show()
    {
        cout << "虚函数实现\n"<< endl;
    }


};


int main()
{
    A a;
    B b;
    A *pa = &a;
    B *pb = &b;
    pa = dynamic_cast<A *>(pb); //子给父可以,
    pb = dynamic_cast<B *>(pa); //父给子不行
    cout << pa->m_a << endl; //结果为100
    cout << pa->m_b << endl;
    pa->show();
   // cout << pa->m_b << endl;
    cout << pb->m_a << endl;
    cout << pb->m_b << endl;
    pb->show();
    return 0;
}


猜你喜欢

转载自blog.csdn.net/zzw_17805056819/article/details/80069702
今日推荐