简体   繁体   English

无法从const char []转换为std:string *

[英]Cannot convert from const char[] to std:string *

In a visual c++ cli project file i created the following class (c++ type) . 在可视的c ++ cli项目文件中,我创建了以下类(c ++类型)。 not able to declere a string or char type suitable for name variable. 无法解析适合名称变量的字符串或char类型。

#include <vector>
#include <string.h>
using namespace std ;

class MyClass 
{
public :
int x;
int y;
string * name;

void foo() { name = "S.O.S" ;}
};

Ps . 附言 type casting err 打字错误

You need to make the following changes: 您需要进行以下更改:

#include <string> // not <string.h>

class MyClass
{
public:
    int x;
    int y;
    string name; // not string*
};

EDIT: 编辑:

To address comments by eliz , a small example: 为了解决eliz的评论,一个小例子:

#include <iostream>
#include <string>

using namespace std;

class MyClass
{
public:
    int x;
    int y;
    string name;

    string foo()
    {
        name = "OK";
        return name;
    }
};

int main()
{
    MyClass m;

    // Will print "OK" to standard output.
    std::cout << "m.foo()=" << m.foo() << "\n";

    // Will print "1" to standard output as strings match.
    std::cout << ("OK" == m.foo()) << "\n";

    return 0;
}

If name is of type string * , then you must call one of the string constructors. 如果name的类型为string * ,则必须调用字符串构造函数之一。

name = new string("S.O.S");

And don't forget to release your string in the destructor (~MyClass())! 并且不要忘记在析构函数(〜MyClass())中释放您的字符串!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 初始化无法从const char [3]转换为std :: string * - Initializing cannot convert from const char [3] to std::string * 无法将&#39;std :: string&#39;转换为&#39;const char * - Cannot convert ‘std::string’ to ‘const char* 无法从&#39;const char *&#39;转换为&#39;std :: _ St​​ring_const_iterator &lt;_Elem,_Traits,_Alloc&gt; - cannot convert from 'const char *' to 'std::_String_const_iterator<_Elem,_Traits,_Alloc> 对于std :: string :: c_str,无法从&#39;const char *&#39;转换为&#39;char *&#39; - cannot convert from 'const char *' to 'char *' for std::string::c_str 无法转换 &#39;std::basic_string<char> &#39; 到 &#39;const char*&#39; 作为参数 &#39;1&#39; 到 &#39;int system(const char*)&#39; - cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' C ++无法将&#39;const char *&#39;转换为&#39;std :: string *&#39; - C++ cannot convert 'const char*' to 'std::string*' 无法转换 std::stringstream<char> 常量字符* - Cannot convert std::stringstream<char> to const char* 如何将 std::string 转换为 const char* 或 char* - How to convert a std::string to const char* or char* 无法将参数1从&#39;CHAR [260]&#39;转换为&#39;const std :: basic_string &lt;_Elem,_Traits,_Ax&gt; - cannot convert parameter 1 from 'CHAR [260]' to 'const std::basic_string<_Elem,_Traits,_Ax> 无法将参数1从&#39;char&#39;转换为&#39;const std :: basic_string &lt;_Elem,_Traits,_Ax&gt;&&#39; - cannot convert parameter 1 from 'char' to 'const std::basic_string<_Elem,_Traits,_Ax> &'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM