为什么我不能调用'explicit a(string x)'? [英] Why I am not able to invoke 'explicit a (string x)'?

查看:174
本文介绍了为什么我不能调用'explicit a(string x)'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用对象a3调用'explicit a(string x)',我有两个编译错误,如:


[Error]从'const char *'到'int'的无效转换[-fpermissive]



< )'[-fpermissive]


我的预期输出是'int int double string';



有人可以帮我删除这些错误吗?感谢您的可能时间。

 #include< iostream& 
#include< string.h>

using namespace std;


struct a {

a(int x = 0){cout<
}
inline a(double x){cout<<double;
}
explicit a(string x){cout<<string;
}

};


int main()
{
a a0(NULL);
a a1 = 9;
a a2 = 1.1;
a a3 =(Widf); //错误
}


解决方案

通过结构/类名调用:

  a(Widf)

使用相等作为构造函数不是显式构造函数调用。
您可以使用:

  a a3 = a(Widf)

这将:


  1. 创建一个临时对象a

  2. 使用复制构造函数创建a3

编译器优化器应能够优化



或者,您可以写

  a a3 (Widf)


I am not able to Invoke 'explicit a (string x)' using the object a3, I got two compilation errors such as:

[Error] invalid conversion from 'const char*' to 'int' [-fpermissive]

[Error] initializing argument 1 of 'a::a(int)' [-fpermissive]

My expected out put is 'int int double string';

Could somebody help me to remove these errors? Thanks for your valuble time.

#include<iostream>
#include<string.h>

using namespace std; 


struct a{

    a(int x=0){cout<<" int ";
    }
    inline a (double x){cout<<" double ";
    }
    explicit a (string x){ cout<<" string ";
    }

};


int main()
{
    a a0(NULL);
    a a1=9;
    a a2=1.1;
    a a3=("Widf"); //Error
}

解决方案

Explicit constructor has to be called via the structure/class name:

a("Widf")

Using an equality as a constructor is not an explicit constructor call. You can use this:

a a3 = a("Widf")

Which will:

  1. Create a temporary object a
  2. Use a copy constructor to create a3

the compiler optimizer should be able to optimize this though.

Alternatively, you can just write

a a3("Widf")

这篇关于为什么我不能调用'explicit a(string x)'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆