除了班级之外的每个人都不变,有这样的事情吗?
Constant for everyone but the class, is there such a thing?
本文关键字:每个人 更新时间:2023-10-16
我一直想知道有没有办法在不使用只能由其类修改的 getter 的情况下拥有一个类成员?
我想的是这样的。
class A
{
public:
crazyconst int x;
void doStuff()
{
// Gettin' stuff done
x = someValue; // OK
}
};
int main(int argc, char** argv)
{
A a;
a.x = 4; // ERROR
}
因此,它是可见的,但对其类旁边的每个人都是只读的。
您的类可以具有对私有的非const
数据成员的公共const
引用。
编辑:但是,我应该指出,这样做会阻止您使用编译器生成的复制构造函数和复制赋值运算符。
答案是否定的,如果没有某种getter,你就无法做到这一点。 但是,您可以使 getter 可重用,并且可以使字段的简单语法(大部分)有效,没有括号。
(C++11 必填)
template<typename Friend, typename FieldType>
class crazyconst
{
FieldType value;
friend Friend;
FieldType& operator=(const FieldType& newValue) { return value = newValue; }
public:
operator FieldType(void) const { return value; }
FieldType operator()(void) const { return value; }
};
class A
{
public:
crazyconst<A, int> x;
void doStuff()
{
// Gettin' stuff done
x = 5; // OK
}
};
int main(int argc, char** argv)
{
A a;
int b = a.x;
int c = a.x(); // also works
}
C++03版本:http://ideone.com/8T1Po
但请注意,这将编译但不能按预期工作:
const int& the_x = a.x;
a.doStuff();
std::cout << the_x;
OTOH,这应该没问题:
const auto& ref_x = a.x;
a.doStuff();
std::cout << ref_x;
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 维护unordered_map但同时每一步都需要最低的映射值
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- Gstreamer:每 5 秒使用多文件墨水保存图像/jpeg
- C++每 x 秒调用一次函数
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 找到一种有效的方法,在 2 个巨大的缓冲区上执行 MAX,每字节字节
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 个人图书馆,数字正数或负数
- C++ 从文本文件中读取每两行,并且在矢量中是安全的
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 如何读取文本文件中的数据并为每列 c++ 分配数组
- 如何在个人计算机和群集 (c++) 上生成相同的随机数
- C++ 尝试优化每一帧将数据打印到二进制文件
- 尝试移动字符串中的每个位
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 如何使路径适应每个人的,计算机