将所有其他实例的值相加,并将此实例设置为该总和

add the value of all other instances and set this instance to that sum

本文关键字:实例 设置 其他      更新时间:2023-10-16

我想获取某个类的任何任意实例;对于此实例,我想在其他实例中添加一个值。 我不希望此实例的值成为总和的一部分。 我编写的代码似乎没有达到这个目标。

我有一个 C++ 类 foo

class foo  
{  
private:  
static int count ;  
int someVar ;  
int anotherVar ;  
void setCount( newCount )  
{  
count = newCount ;  
}  
public:  
void doSomething(void)  
{  
while ( index < count - 1 )  
{  
// don't do the calculation  
// when this instant is the  
// one having its version of  
// anotherVar updated  
if ( foo == this-> ?? )  
{  
continue ;  
}  
someVar += anotherVar ;  
index++ ;  
}  
}  
} ;  

换句话说,我有一个 foo 实例的向量。 我想将任意一个实例从其余实例中添加另一个另一个 Var 到该实例的 someVar 值。

总的来说,我将遍历 foo 的所有实例,以将此 otherVar 设置为当前交互实例的所有其他实例的 someVar。

你不能只是凭空魔术foo引用,你必须将它们提供给方法。

template<typename Iterator>
foo::doSomthing(Iterator iter, Iterator end)
{
for (; iter != end; ++iter)
{
if (&*iter == this) { continue; }
someVar += iter->otherVar;
}
}
int main ()
{
std::vector<foo> foos = { /* some foos*/ };
foos.front().doSomething(foos.begin(), foos.end());
}