zoukankan      html  css  js  c++  java
  • 【c++】explicit 隐式类类型转换

    上代码

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    class A 
    {
        public:
            A(const string &book = "ab") : s(book)  {}
            int same_s(const A &a) const
            { return s == a.s; }
        private:
            string s;
    };
    
    int main(int argc ,char **argv)
    {
        A c("aaa");
        string m = "aaa";
        cout << c.same_s(m) << endl;
    }

    究其因

    same_s应该接收一个类A的对象参数,但是这里直接传了一个字符串对象。过程这样:编译器接收一个string的对象,利用构造函数 A(const string &book = "ab") 生成临时对象(隐性转换),然后传递给same_s,临时对象失效.

     注意: explicit 只能用于类内部的构造函数的声明上。

    explicit和构造函数一起使用.
    explicit constructor指明构造函数只能显式使用,目的是为了防止不必要的隐式转化.

    如何防止隐性转换

    构造函数加关键字explicit

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    class A 
    {
        public:
            explicit A(const string &book = "ab") : s(book)  {}
            int same_s(const A &a) const
            { return s == a.s; }
        private:
            string s;
    };
    
    int main(int argc ,char **argv)
    {
        A c("aaa");
        string m = "aaa";
        cout << c.same_s(m) << endl;
    }

    结果出错

    解决之道

    字符串强制传递给构造函数

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    class A 
    {
        public:
            explicit A(const string &book = "ab") : s(book)  {}
            int same_s(const A &a) const
            { return s == a.s; }
        private:
            string s;
    };
    
    int main(int argc ,char **argv)
    {
        A c("aaa");
        string m = "aaa";
        cout << c.same_s(A(m)) << endl;
    }

    同理

    对于 A a = string("hello")来说,如果参数为string的构造函数为explicit,则这样初始化是错误的;如果不是explicit,则这样初始化是正确的(先利用构造函数生成临时对象,再把临时对象通过赋值操作符复制到新创建的对象上)。

    对比实验

     

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    class A 
    {
    	public:
    		A(const string a) : s(a) {}
    	private:
    		string s;
    };
    int main(int argc ,char **argv)
    {
    	A a = string("hello");
    } 

    #include <iostream>
    #include <sstream>
    using namespace std;
    
    class A 
    {
    	public:
    		explicit A(const string a) : s(a) {}
    	private:
    		string s;
    };
    int main(int argc ,char **argv)
    {
    	A a = string("hello");
    }
    

      

  • 相关阅读:
    美国队长清晰TC中字 迅雷下载+ 美国队长 漫画 复仇者迅雷下载
    【转】腾讯、人人、新浪社交网络优劣势分析(转自月光博客)
    【技术贴】NVIDIA控制面板设,显示屏输入信号超出范围
    【技术贴】怎么拖动vs2008的控件
    SQL Server 2000/2005检测存储过程名是否存在,存在删除
    asp.net生成HTML
    gridview列 数字、货币和日期 显示格式
    用C#编写托盘程序
    判断地址栏参数,为空或null
    C# 读取计算机CPU,HDD信息
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3479458.html
Copyright © 2011-2022 走看看