作者littleshan (我要加入剑道社!)
看板C_and_CPP
标题Re: [问题] c++的constructor使用问题
时间Wed Apr 1 09:30:40 2009
※ 引述《KATORU (欢迎加入NHK!!!)》之铭言:
: compiler後, error问题都会在if (obj.getDollar())这行
: 说明是说"obj没有宣告"
: 然後我看了一下, 问题似乎都在这个if判断式
: if (max<=0)
: { Counter obj; system ("cls");}
: else
: { Counter obj(max); system ("cls");}
: 我将这整段if else都拿掉, 改成Counter obj; 之後
: compiler就会过了...
: 想请问一下这边是本来就不能这样用吗!?
: 还是我忘记定义什麽...@@
: 谢谢
话说,这个问题可以用 RVO 来解决
inline Counter CreateCounter(int max)
{
if(max <= 0)
return Counter();
else
return Counter(max);
}
int main()
{
...
Counter obj = CreateCounter(max);
...
}
或着说你这样写:
Counter obj = ( max <= 0 ? Counter() : Counter(max) );
我用 gcc 测过
两者都不会多出额外的 copy constructor
这个方法会比 new 还快,而且安全
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 219.87.151.2