随笔 - 8  文章 - 26  trackbacks - 0
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

常用链接

留言簿(4)

随笔档案

文章分类

文章档案

相册

C++语言

搜索

  •  

最新评论

阅读排行榜

评论排行榜

一个explicit关键字声明的构造函数禁止编译器进行隐式类型转换 .(禁止单参数构造函数"被用于自动型别转换
参考如下代码:
 1#include <stdio.h>
 2#include <iostream>
 3
 4using namespace std;
 5
 6
 7
 8
 9class C 
10{
11public:
12    int i;
13    C(const C&)   // an  copy constructor
14    {
15        printf("\nin the copy constructor");
16    }

17    explicit C(int i )   // an explicit constructor
18    {
19        printf("\nin the constructor");
20    }

21
22    operator int()const //classs ->int
23    {
24        printf("\noperator int()");
25        return i;
26    }

27
28    C()
29    {
30        i = 0;
31    }

32}
;
33
34void test_fun1(C obj);
35void test_fun2(int i);
36void test_fun3(C c);
37
38
39int main()
40{
41    C c, d;
42    test_fun3(c);   // c is copied
43
44    //test_fun1(1);//错误,因为构造函数声明了explicit,所以禁止隐式转换
45
46    test_fun2(c); //call operator int()const
47    test_fun1(c);
48    cin.get();
49    return 0;
50}

51
52void test_fun1(C obj)
53{
54}

55
56void test_fun2(int i)
57{
58}

59
60void test_fun3(C c)
61{
62}
从网上看到这段代码:
 1#include <string>
 2#include <iostream>
 3
 4using namespace std;
 5
 6class Number {
 7    public:
 8        string type; 
 9
10        Number(): type("void"{ }
11      explicit   Number(short) : type("short"{ } 
12        Number(int) : type("int"{ }
13    }
;
14    void Show(const Number& n) { cout << n.type; }
15    void f()
16    {
17        short s = 42;
18        Show(s); 
19    }

20int main()
21{
22f();
23cin.get();
24return 0;
25}

26
这段代码的返回值为:int,这里面起关键作用的就是那个explicit


posted on 2008-06-25 21:36 杨彬彬 阅读(164) 评论(0)  编辑 收藏 引用 所属分类: C++语言

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理