return*this c ++

shi*_*zle 2 c++ return-type void

如果你有一个清除数组中所有元素的clear()函数,你是否使用void类型或referens到你正在使用的类型并返回*this.

防爆.

void Vector<T>::clear() {   
}
Run Code Online (Sandbox Code Playgroud)

要么

Vector& Vector<T>::clear(){
    return *this
}
Run Code Online (Sandbox Code Playgroud)

我真的不明白何时返回"this"以及何时使用void类型.

Cod*_*aos 9

我假设返回*this对链API调用很有用.obj.doSomething().doSomethingElseAfterwards().所以称链接是有用的,比如add是很好的候选者*this.链接不是很有用的方法可能会返回void.

就我个人而言,我并不喜欢这种链式,但很多人都喜欢这种流畅的API.