public:
string str;
Test(string& str){
this->str=str;
cout<<"constructor"<<endl;
}
};
int main() {
Test t="test";
return 0;
}
In this code I get the error "..\src\Test.cpp:30:9: error: conversion from 'const char [5]' to non-scalar type 'Test' requested "?
Why is then the following code ok?
#include <iostream>
using namespace std;
class Test{
public:
string str;
Test(string str){
this->str=str;
cout<<"constructor"<<endl;
}
Test(const Test &test){
cout<<"copy constructor"<<endl;
this->str=test.str;
}
};
int main() {
Test t=Test("test");
return 0;
}
Test t="test";
This tries to:
char[5]) into a temporary stringstring to TestThis fails for two reasons:
Test(string&) wants.Your second example fixes these problems by:
string to Test explicit, Test(...). Now there is only one implicit conversion, from char[5] to string. Note that this is rather a verbose way to initialise it; Test t("test") would do the same thing.string by value, not reference. A const reference, const string&, would also work, as would a const char*.Both of these changes are necessary, since each fixes just one of the two problems.
You are only allowed one implicit conversion between user defined types. Your code has an implicit conversion from const char[6] (which decays to const char*) to std::string, and from std::string to Test. This is the reason changing the signature to Test(const std::string&) will not work.
Try changing the constructor signature to
#include <string>
struct Test
{
Test(const char* c) : s_(c) {}
std::string s_;
};
int main()
{
Test t = "Hello";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With