• C++ 关键字explicit的使用场景


    假若我们定义了Str类如下结构

    class Str
    {
      public:

        Str(int n)

        Str(const char* p)

      .....

    }

    可以使用如下方式来构建一个对象  

    Str c(12);
    Str d=Str(20);
    Str *z=new Str(21);
    Str a=10;//此处构建10个大小的空间
    Str b="abcd";//此处构建特定字符串大小空间
    Str f='f';   //与设计不相符的构建方式,这里会构建(int)'f'大小的内存空间

     

     

    也许调用者是希望Str存'f'这一个字符,尽管Str没有提供这样的接口,但是编译的时候并不会报错,因为这里存在隐式转换,将char型转换为Int型,这样就与调用者的初衷不符合了。而使用explicit可以杜绝这种隐式转换,在编译的时候就不会让其通过。可见explicit对于写一些基础库供他人调用还是非常有必要的.

    代码:

    #include<iostream>
    using namespace std;
    
    class Str
    {
    public:
    /*      explicit*/  Str(int n)//try explicit here
            {
                    capacity=n;
                    getmem();
            }
            Str(const char* p)
            {
                    capacity=strlen(p)+1;
                    getmem();
                    strcpy(strarr,p);
            }
            ~Str()
            {
                    if(strarr!=NULL)
                            free(strarr);
            }
            void printfvalue()
            {
                    cout<<"len:"<<capacity<<"    str:"<<strarr<<endl;
            }
    private:
            void getmem()
            {
                    strarr=(char*)malloc(sizeof(char)*capacity);
            }
    private:
            int  capacity;
            char *strarr;
    };
    
    int main()
    {
            Str c(12);
            Str d=Str(20);
            Str *z=new Str(21);
            Str a=10;
            Str b="abcd";
            Str f='f';
            c.printfvalue();
            d.printfvalue();
            z->printfvalue();
    
            a.printfvalue();
            b.printfvalue();
            f.printfvalue();
            return 1;
    }

      


    博客地址:Zealot Yin

    欢迎转载,转载请注明出处[http://creator.cnblogs.com/]

  • 相关阅读:
    sublime3使用
    内存缓存 ehcache
    一些服务端写代码的规范,很重要
    对于算法的一点思考
    使用单元测试引发的一些思考
    在多线程中使用spring的bean
    一个线上缓存异常
    java 中的同步机制
    微服务中的集成测试
    服务升级中的zookeeper
  • 原文地址:https://www.cnblogs.com/Creator/p/2602354.html
Copyright © 2020-2023  润新知