more effective c++(cast pleacementNew explicit)

来源:互联网 发布:推荐算法常用数据集 编辑:程序博客网 时间:2024/05/18 03:49

之前看的书写的代码都没有保存,以至现在都找不到了。还是保存一下吧。。以后还可以拿来看

前四章,类型转化 指针操作多态数组 隐士类型转化。代码中稍许注释,仅限自己看懂。。。

知识点:

1 const_cast 去掉const限制,仅限引用和指针

2 不能两次调用用户定义隐式类型转换,但是可以一次内置一次用户自定义

3 operator delete[](rawMemoty)正确释放raw内存

4 不能用指针操作多态数组

#include <iostream>using namespace std;class A {    int a;public:    A(int aa = 0):a(aa) {    }    void updateAndShow(){        a += 10;        cout << a << endl;    }};int main(int argc, char* argv[]) {    const A a(static_cast<int>(19.5));    const A& aa = a;    //const_cast<A>(a).updateAndShow(); error 只能强转成引用或指针    const_cast<A&>(aa).updateAndShow(); // 只能强转成引用或指针    return 0;}

#include <iostream>#include <cstdio>using namespace std;class A{public:    A(int a, int b = 0): _a(a), _b(b) {        cout << "A(int, int)" << endl;    }    explicit A(double a, double b=0): _a( static_cast<int>(a) ), _b( static_cast<int>(b) ){    }    operator double() const {        return static_cast<double>(_a);    }    void show() const{        cout << _a << " " << _b << endl;    }private:    int _a, _b;};class B{public:    B(A a): _a(a){    }    void show() const {        cout << "in B:" << endl;        _a.show();    }private:    A _a;};void show(const A& a) {    a.show();}void showB(const B& b) {    b.show();}int main(int argc, char* argv[]){    A a(10);    a.show();    cout << a << endl;    show(10);    show(10.0); //可以正常编译,先转int然后调用A(int, int)    //showB(10); 不能调用两次用户定义隐式类型转换    showB(A(10));    return 0;}

#include <iostream>#include <vector>using namespace std;class A{    int a;public:    A(int a): a(a) {    }    void show(){        cout << a << endl;    }    ~A(){        cout << "des" << endl;    }};int main(int argc, char* argv[]) {    //vector< A > v(10); no default constructor error    vector< A > v;    void * rawMemory = malloc(10 * sizeof(A));    A* pa = static_cast<A*>(rawMemory);    for(int i=0; i<10; ++i) {        new(pa+i) A(i);        pa[i].show();    }    for(int i=0; i<10; ++i) {        pa[i].~A();    }    //delete[] pa;  对于不是new的数组,使用delete[] 无意义,运行时报错    operator delete[](rawMemory); //正确的释放raw 内存方式    return 0;}

#include <iostream>using namespace std;class A {    int a;public:    A():a(10){}    virtual void show() const{        cout << a << endl;    }};class B: public A {    int b, c, d;public:    B():A::A(), b(20){    }    virtual void show() const{        A::show();        cout << " " << b << endl;    }};void print(const A * x, int len) {    for(int i=0; i<len; ++i) {        x[i].show(); //x的类型为A,指针计算偏移按照sizeof(A),而数组里面实际是B。。这样导致地址计算错误    }    delete [] x;//同样错误}int main(int argc, char* argv[]){    A a;    B b;    a.show();    b.show();    B bb[10];    cout << sizeof(A) << " " << sizeof(B) << endl;    print(bb, 10);    return 0;}

0 0