有没有办法拥有动态默认参数?
我正在尝试创建一个类,用户可以在其中修改成员变量以更改其成员函数的默认参数。
class Class
{
public int Member;
public void Method(int Argument = Member)
{
// This compiles fine, until I try to actually use
// the method elsewhere in code!
// "Error: need 'this' to access member Member"
}
}
到目前为止,我的解决方法是使用幻数,这显然并不理想。
public void Method(int Argument = 123)
{
int RealArgument;
if (Argument == 123) RealArgument = Member;
else RealArgument = Argument;
}
有没有更好的方法,或者我是否坚持这个“黑客”解决方案?
I'm trying to make a class where the user can modify member variables to change the default arguments of its member functions.
class Class
{
public int Member;
public void Method(int Argument = Member)
{
// This compiles fine, until I try to actually use
// the method elsewhere in code!
// "Error: need 'this' to access member Member"
}
}
My workaround so far has been to use magic numbers, which obviously isn't ideal.
public void Method(int Argument = 123)
{
int RealArgument;
if (Argument == 123) RealArgument = Member;
else RealArgument = Argument;
}
Is there a better way, or am I stuck with this "hack" solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,忘记默认参数。
这里不需要诡计。
Yep, forget about the default argument.
No need for trickery here.