问题
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
}
回答1:
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:
- Create a temporary object a
- 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")
回答2:
Syntactically, C++ interprets
a a3 = ("Widf");
As "evaluate the expression "Widf"
, then construct an object of type a
called a3
that is initialized to be equal to it." Since "Widf"
has type const char[4]
, C++ will only be able to initialize a3
to "Widf"
if there is an implicit conversion constructor available. Since you've explicitly marked the constructor explicit
, this implicit conversion isn't available, hence the error.
To fix this, try rewriting the line as
a a3("Widf");
This doesn't try to evaluate "Widf"
first, but instead directly passes it as a parameter to the constructor.
Hope this helps!
来源:https://stackoverflow.com/questions/15049542/why-i-am-not-able-to-invoke-explicit-a-string-x