class test
{
public:
string str;
Test(string& str){
this->str=str;
cout<<"constructor"<<endl;
}
};
int main() {
Test t="test";
return 0;
}
error: conversion from 'const char [ ]' to non-scalar type
解决办法
1
#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;
}
2
#include <string>
struct Test
{
Test(const char* c) : s_(c) {}
std::string s_;
};
int main()
{
Test t = "Hello";
}
3
Test t("test");
or
Test t = string("test");
参考