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

问题描述:

在visual C++ cli项目文件中,我创建了以下类(C++类型)。 无法删除适合名称变量的字符串或字符类型。无法从const char []转换为std:string *

#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。型铸造ERR

+4

它是'#include '不是'#include '。 – 2012-02-07 13:05:50

你需要做以下修改:

#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; 
} 
+0

或者他可以使用'name = new string(“S.O.S”),但是如果没有复制构造函数,这将是相当危险的 – Petesh 2012-02-07 13:08:32

+0

@Petesh,我打算暗示,但是决定使用'string'更简单。 – hmjd 2012-02-07 13:09:18

+0

@hmjd我如何检查你的答案字符串foo(){name =“OK”;返回名称;} – eliz 2012-02-07 13:12:22

如果name是类型string *,那么你必须调用其中一个字符串构造函数。

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

并且不要忘记在析构函数(〜MyClass())中释放你的字符串!

+0

复制构造函数和赋值运算符也需要实现,因为默认版本不够。 – hmjd 2012-02-07 13:21:59

+0

是的,对于每个拥有动态数据的课程来说,四大必需品。 – Alexander 2012-02-07 13:30:07

+0

@hmjd(m.foo())不起作用。它应该是m-> foo() – eliz 2012-02-07 13:31:19