首页 新闻 赞助 找找看

一个c++构造函数的疑问

0
悬赏园豆:10 [待解决问题]
//#include <iostream>
//using namespace std;
#include <Windows.h>

class student
{
public:
    student(){OutputDebugStringA("student()\n");}
    /*explicit */student(const char* s){OutputDebugStringA("student(const char* s)\n");}
    student(const student& stu){OutputDebugStringA("student(const student& stu)\n");}
    student& operator = (const student& stu){OutputDebugStringA("student& operator = (const student& stu)\n"); return *this;}
};
int main() { student s1; OutputDebugStringA("\n"); student s2("11"); OutputDebugStringA("\n"); student s3 = "11"; OutputDebugStringA("\n"); student s4 = s3; OutputDebugStringA("\n"); student s5; s5 = "11"; OutputDebugStringA("\n"); student s6; s6 = s5; return 0; }

输出为:

student()

student(const char* s)

student(const char* s)

student(const student& stu)

student()
student(const char* s)
student& operator = (const student& stu)

student()
student& operator = (const student& stu)

这样的结果我可以理解, 但是如果将代码中的注释去掉,编译的时候 student s3 = "11"; 就出错了, 但是这个不是调用的是 student(const char* s)吗? 这个没有隐式转换啊,为什么会出错呢?

提示是:

error C2440: 'initializing' : cannot convert from 'const char [3]' to 'student'

  

likebeta的主页 likebeta | 初学一级 | 园豆:179
提问于:2012-08-29 11:21
< >
分享
所有回答(2)
0
explicit是~防止! 隐式转型。Google一下吧。
irons | 园豆:11 (初学一级) | 2012-09-02 22:27

不加的时候, 是相当于student s3 =student("11");还是student s3("11"); ?

支持(0) 反对(0) likebeta | 园豆:179 (初学一级) | 2012-09-07 16:11
0

如果你把注释去掉了,那么explicit起到作用,就会禁止隐式转换。student s3 = "11"当然编译不通过了,只能用student s3 =student("11");或者student s3{"11"};

第五元素~MJ | 园豆:6 (初学一级) | 2012-09-07 16:02

不加的时候, 是相当于student s3 =student("11");还是student s3("11"); ? 或者说student s3 =student("11");和student s3("11");是否为一样的?

支持(0) 反对(0) likebeta | 园豆:179 (初学一级) | 2012-09-07 16:12

@likebeta: student s3 =student("11")和student s3("11")和student s3{"11"}这三种表达方式是等价的,不管有没有expliciti都可以用。而student s3="11",右边值是一个字符串,但是左边s3是一个对象,所以它有一个隐式的转换。加上explicit之后相当于禁止了这种转换。

支持(0) 反对(0) 第五元素~MJ | 园豆:6 (初学一级) | 2012-09-07 16:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册