【发布时间】:2016-03-20 16:43:07
【问题描述】:
说我有这个方法:
bool match( /* some optional parameter */ );
这将做一些字符串模式匹配,我想允许它被赋予一个可选参数,当方法match()返回true时,该参数只会填充一个已知类型的实例(Match),这样的事情可能吗?
在 PHP 中我可以这样做:
public function match( Match &$match = null ) {
if( someMatchingRoutineMatched() ) {
$match = new Match();
return true;
}
return false; // $match will stay null
}
然后这样称呼它:
// $test is some instance of the class that implements match()
// I don't have to declare $m up front, since it will be filled by reference
if( $test->match( $m ) ) {
// $m would be filled with an instance of Match
}
else {
// $m would be null
}
在 c++ 中是否有类似的可能?
我已经让它与以下内容一起工作
bool match( Match*& match ) {
if( /* something matches */ ) {
match = new Match;
return true;
}
return false;
}
...然后这样称呼它:
Match* m = nullptr; // I wish I wouldn't have to declare this upfront as a nullptr
if( test.match( m ) ) {
// a match occured, so m should no longer be a null pointer
// but let's just make sure
if( m != nullptr ) {
// do something useful with m and afterwards delete it
delete m;
}
}
...然而,这一切都感觉有点麻烦。此外,我似乎不允许将参数设为可选,例如:
bool match( Match*& match = nullptr );
...因为我相信引用不允许为空,对吗?
我希望您能看到我正在努力实现的目标,并希望您能就我如何实现我的目标提供一些见解,如果有可能的话。
【问题讨论】:
-
有两个重载,一个什么都不带,另一个和你一样,但没有默认值。
-
@DanMašek 好的,这将解决可选位,但是当
match()返回false时,是否仍有办法将match保持为null?基本上,我想要实现的是保证match将仅在确实找到匹配项时填充Match的实例,并且否则为null。我希望这是有道理的。 -
是的,请看下面的答案。
-
在
C++和PHP中,您可以返回NULL而不是false和新对象而不是true。如果方法返回的值不是NULL,那么调用代码可以将它存储到您传递给match()的变量中。这样,当$m的值发生变化时,读者就很清楚了(现在必须阅读函数 match() 的代码才能了解这一事实。)
标签: c++ pass-by-reference optional-parameters nullptr