假設我有一堂課:
class LiveEntity
{
public:
int example = 5;
};
現在,在我的主檔案中,我有該類的兩個物件:
LiveEntity Box[7];
Box->example = 0;
LiveEntity Circle[7];
Circle->example = 2;
有沒有辦法讓我同時更改 Circle->example 和 Box->example 而不必單獨撰寫它們?假設我希望它們每幀都 = 一定的增量,而不必在 for 回圈中一個接一個地撰寫它們。在我實際的 main.cpp 中,我有大約 10 個不同的“LiveEntity”類物件,我希望它們都受到相同添加的影響。
基本上,目前,它看起來像這樣:
for (int x = 0; x < 7; x ){
Box[x].example = increment;
Circle[x].example = increment;
// and 8 more.
}
uj5u.com熱心網友回復:
for (int i = 0; i < 7; i )
{
for (LiveEntity *arr : {Box, Circle})
arr[i].example = increment;
}
uj5u.com熱心網友回復:
std::valarray可能有一種解決方法(可能性)。
例子:
#include <iostream>
#include <valarray>
class LiveEntity {
public:
int example = 5;
//we need a default and for convenience an implicit value constructor
LiveEntity(int val = 5) noexcept : example(val) {}
//to avoid the implementation of each operator
//we implement user-defined conversion methods
operator int () const noexcept { return example; }
operator int& () noexcept { return example; }
};
//if no user-defined conversion was implemented,
//each operator has to be implemented
//@see https://en.cppreference.com/w/cpp/numeric/valarray/operator_arith2#Notes
LiveEntity& operator = (LiveEntity& lhs, LiveEntity rhs) noexcept
{
lhs.example = rhs.example;
return lhs;
}
int main()
{
//valarray instead of array
std::valarray<LiveEntity> arr(5);
//print the default instantiated elements
for (auto e : arr) {
std::cout << e.example << std::endl;
}
//increase by 1
//without implicit value constructor,
//something like arr = LiveEntity(1) has to be used
arr = 1;
//print the incremented values
for (auto e : arr) {
std::cout << e.example << std::endl;
}
return 0;
}
uj5u.com熱心網友回復:
也許你可以定義一個靜態成員變數來存盤類的所有實體,并定義一個函式來一一更新它們。
#include <iostream>
#include <set>
using namespace std;
class LiveEntity
{
public:
LiveEntity() { instances_.insert(this); }
~LiveEntity() { instances_.erase(this); }
public:
int example = 5;
public:
static void IncrAll(int v)
{
for (auto instance : instances_)
instance->example = v;
}
public:
static set<LiveEntity*> instances_;
};
set<LiveEntity*> LiveEntity::instances_;
void Test()
{
LiveEntity le1;
LiveEntity le2;
LiveEntity le3;
le1.example = 1;
le2.example = 2;
le3.example = 3;
cout << le1.example << " " << le2.example << " " << le3.example << endl; // 6 7 8
LiveEntity::IncrAll(3);
cout << le1.example << " " << le2.example << " " << le3.example << endl; // 9 10 11
}
int main()
{
cout << LiveEntity::instances_.size() << endl;
Test();
cout << LiveEntity::instances_.size() << endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425844.html
