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

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

本文关键字:std string 转换 const-char      更新时间:2023-10-16

在一个可视化的c++cli项目文件中,我创建了以下类(c++类型)。无法清除适合名称变量的字符串或字符类型。

#include <vector>
#include <string.h>
using namespace std ;
class MyClass 
{
public :
int x;
int y;
string * name;
void foo() { name = "S.O.S" ;}
};

p.s.类型铸造错误

您需要进行以下更改:

#include <string> // not <string.h>
class MyClass
{
public:
    int x;
    int y;
    string name; // not string*
};

编辑:

为了解决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;
}

如果name的类型为string *,则必须调用其中一个字符串构造函数。

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

不要忘记在析构函数(~MyClass())中释放字符串!