将字符串文本传递给函数并赋值给成员变量
Passing string literal to function and assign to member variable
这可能是一个新手问题,但我无法解决这个问题。我可以分别解决前一个或后一个问题,但不能同时解决。
我有一个类,它有一个字符串成员,还有一个函数来设置它。我想给函数传递一个文本。
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*指针。
相关文章:
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- 清除具有已删除赋值运算符的成员的类实例
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 静态成员函数赋值而不带返回语句
- 我们可以直接为任何数据成员赋值. 为什么要使用构造函数?
- 使用 boost python 从 c++ 为 python 中的类成员变量赋值
- Clang 无法在赋值运算符/复制构造函数中检测到未初始化的类成员
- 通过智能指针向类成员进行赋值
- 是否应该在复制构造函数或赋值运算符中复制静态数据成员
- Gcc 使用 memcpy 作为隐式复制赋值运算符,而不是成员复制
- C++ 包含唯一指针成员变量的类的赋值运算符
- 是否有必要重载具有另一个类 B 的数据成员的类 A 的赋值运算符和复制构造函数?
- 我们不能在未赋值的上下文中命名非静态成员函数是有原因的吗
- 通过迭代器为映射的成员赋值
- 为什么不能为基类的成员赋值?
- 如何使用其他函数返回的值为结构体成员赋值
- 什么是成员数据指针的正确赋值语句
- STL - 赋值运算符与“赋值”成员函数
- 在可选结构成员中赋值成员