简体   繁体   English

如何避免构造函数中的冗余计算

[英]How to avoid redundant computation in constructors

I've got a constructor like so: 我有一个像这样的构造函数:

C(T x) : base(f(x))
{
   ...
   do something with f(x)
   ...
}

f(x) is not exposed as a member in the base class. f(x)没有公开为基类的成员。 How do I avoid calculating f(x) twice if I can't modify C s base? 如果无法修改C的基数,如何避免两次计算f(x)

You could use two constructors, for example: 您可以使用两个构造函数,例如:

private C(WhateverFReturns x) : base(x)
{
    //do something with x
}

public C(T x) : this(f(x))
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM