質問

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
}
役に立ちましたか?

解決 2

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")

他のヒント

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!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top