【问题标题】:Cannot convert from const char[] to std:string *无法从 const char[] 转换为 std:string *
【发布时间】:2012-02-07 21:36:56
【问题描述】:

在一个可视的 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" ;}
};

附言。类型转换错误

【问题讨论】:

  • 这是#include &lt;string&gt; 而不是#include &lt;string.h&gt;

标签: c++ visual-c++ c++-cli


【解决方案1】:

您需要进行以下更改:

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

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

编辑:

通过eliz寻址cmets,一个小例子:

#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 = new string("S.O.S"),但如果没有复制构造函数,那将非常危险
  • @Petesh,我打算这样做,但决定使用 string 更简单。
  • @hmjd 我如何检查你的答案字符串 foo() {name = "OK";返回名称;}
  • 如果您的意思是检查它是否正常工作,那么只需比较返回值:if ("OK" == m.foo()),其中mMyClass 的一个实例。
  • @hmjd 我如何检查您的答案。字符串 foo() {name = "OK";返回名称;}
【解决方案2】:

如果name 的类型为string *,那么您必须调用字符串构造函数之一。

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

别忘了在析构函数中释放你的字符串 (~MyClass())!

【讨论】:

  • 复制构造函数和赋值运算符也需要实现,因为默认版本不够。
  • 是的,对于每个有动态数据的类来说,四大都是必要的。
猜你喜欢
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多