c 语言 函数参数默认值,在C ++中通过引用传递时参数的默认值

已经在对您的答案的直接评论之一中说过,但只是正式声明。您要使用的是重载:

virtual const ULONG Write(ULONG &State, bool sequence);

inline const ULONG Write()

{

ULONG state;

bool sequence = true;

Write (state, sequence);

}

使用函数重载也有其他好处。首先,您可以默认使用任何您想要的参数:

class A {};

class B {};

class C {};

void foo (A const &, B const &, C const &);

void foo (B const &, C const &); // A defaulted

void foo (A const &, C const &); // B defaulted

void foo (C const &); // A & B defaulted etc...

也可以将默认参数重新定义为派生类中的虚函数,这样可以避免重载:

class Base {

public:

virtual void f1 (int i = 0);  // default '0'

virtual void f2 (int);

inline void f2 () {

f2(0);                      // equivalent to default of '0'

}

};

class Derived : public Base{

public:

virtual void f1 (int i = 10);  // default '10'

using Base::f2;

virtual void f2 (int);

};

void bar ()

{

Derived d;

Base & b (d);

d.f1 ();   // '10' used

b.f1 ();   // '0' used

d.f2 ();   // f1(int) called with '0'

b.f2 ();   // f1(int) called with '0

}

只有一种情况是真正需要使用默认值,那就是构造函数。不可能从另一个构造函数中调用一个构造函数,因此该技术在这种情况下不起作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值