强制c++类实例在复制或赋值时更改成员值
Force C++ class instances to change member value when copied or assigned
我有一个名为Solution
的类定义如下。我只包含了相关的代码,并且我已经而不是编写了自定义复制或赋值操作符。
class Solution {
public:
Solution() {
stream.setNewSeed(seedShift+static_cast<long>(12345));
++seedShift;
}
RandomNumberStream stream;
private:
static long seedShift = 0;
};
这里的要点是,我希望Solution
的每个新实例具有不同的随机数流。这工作。
问题是,然而,有一些地方我从std::vector<Solution>
复制Solution
的实例,稍微修改它,然后将副本推到相同的std::vector<Solution>
上。当这种情况发生时,我有两个具有相同随机数seed的Solution
实例,灾难随之而来。
我怎样才能使stream.setNewSeed(seedShift+static_cast<long>(12345));
和++seedShift;
语句在被推到矢量上的复制Solution
实例中运行?
重载赋值操作符。注意——这也意味着当你从vector中读取值和/或复制vector本身时,随机数seed也会再次改变。
class Solution {
public:
Solution() {
stream.setNewSeed(seedShift+static_cast<long>(12345));
++seedShift;
}
Solution& operator=(Solution& other)
{
stream.setNewSeed(seedShift+static_cast<long>(12345));
++seedShift;
x = other.x;
y = other.y;
z = other.z;
return *this;
}
RandomNumberStream stream;
private:
static long seedShift = 0;
};
压入vector
将使用复制构造函数(或移动构造函数,但我们将使其简单,并假设它现在使用复制构造函数)。它具有签名:
Solution(const Solution& rhs);
然后您可以相当简单地实现此逻辑:
Solution(const Solution& rhs)
{
stream.setNewSeed(seedShift + 12345L);
++seedShift;
}
注意,如果你实现了这个,你可能也应该实现复制赋值操作符:
Solution& operator=(const Solution& rhs)
{
if(this != &rhs) {
stream.setNewSeed(seedShift+static_cast<long>(12345));
++seedShift;
}
return *this;
}
相关文章:
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- 清除具有已删除赋值运算符的成员的类实例
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 静态成员函数赋值而不带返回语句
- 我们可以直接为任何数据成员赋值. 为什么要使用构造函数?
- 通过迭代器为映射的成员赋值
- 为什么不能为基类的成员赋值?
- 如何使用其他函数返回的值为结构体成员赋值
- C++:为类中对象的数据成员赋值
- 如何为所有结构成员赋值
- 使用双指针为结构的成员赋值
- C++:成员赋值如何工作
- 用方法代替成员赋值
- 在c++中快速将基对象的所有成员赋值给派生对象
- 返回值函数中结构成员赋值的额外拷贝
- 将pair的成员赋值给变量
- c++在使用类方法给成员赋值时每次都会崩溃
- 成员赋值笛卡尔类 c++
- c++扑克游戏中的数据成员赋值