将字符串文本传递给函数并赋值给成员变量

Passing string literal to function and assign to member variable

本文关键字:赋值 成员 变量 函数 文本 字符串      更新时间:2023-10-16

这可能是一个新手问题,但我无法解决这个问题。我可以分别解决前一个或后一个问题,但不能同时解决。

我有一个类,它有一个字符串成员,还有一个函数来设置它。我想给函数传递一个文本。

class Profiler
{
private:
    std::string description;
    //snip
public:
    //snip
    void startJob(const std::string &desc);
};

void Profiler::startJob(const string &desc) {
    //snip
    description = desc;
}

我想(实际上需要)这样使用它:

profiler.startJob("2 preprocess: 1 cvConvertScale");

问题是:

  • 如何将字符串文本传递给函数?我能找到的答案是:通过值传递,或者通过常量指针或常量引用传递。我不想按值传递它,因为它很慢(毕竟它是一个探查器,精确到微秒)。Const指针/引用给出编译器错误(或者我做错了什么?)

  • 如何将其分配给成员函数?我能找到的唯一解决方案是将成员变量设置为指针。使其成为非指针会导致错误"字段‘description’的类型不完整"(wtf这意味着什么?)。将其作为指针是不起作用的,因为它会将常量分配给非常量。似乎只有const指针/引用有效。

按引用传递,按值存储,包括标题:

#include <string>
class Profiler {
  private:
    std::string description;
    //snip
  public:
    //snip
    void startJob(const std::string &desc);
};
void Profiler::startJob(const string &desc) {
  //snip
  description = desc;
}

只要不修改原始字符串,就可以按值存储。如果你不这样做,它们将共享内存,并且不会出现低效的复制。不过,在这种情况下,您将把字符复制到由std::string控制的缓冲区中。

我认为不可能将指向文字char*的指针存储为std::string的实例,尽管可以存储char*指针。