在visual 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。 type casting err
答案 0 :(得分:6)
您需要进行以下更改:
#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;
}
答案 1 :(得分:2)
如果name
的类型为string *
,则必须调用其中一个字符串构造函数。
name = new string("S.O.S");
不要忘记在析构函数中释放你的字符串(~MyClass())!