我们来介绍这个简单的例子:
#include <cmath>
class X
{
public: // Members
/// A ^ B + A
int A;
/// A ^ B + B
int B;
public: // Specials
X(
const int & A,
const int & B
)
: A(A)
, B(B)
{
const auto Pow = static_cast<int>(std::pow(A, B));
this->A += Pow;
this->B += Pow;
}
};
A
和B
。A ^ B + A
和A ^ B + B
。std::pow
很复杂)。我想让A
和B
成员const
。
怎么做而不重复复杂的初始化(即避免两次调用std::pow
)?
#include <cmath>
class X
{
public: // Members
/// A ^ B + A
const int A;
/// A ^ B + B
const int B;
public: // Helpers
struct Init
{
public: // Members
int A;
int B;
public: // Specials
Init(
const int & A,
const int & B
)
: A(A)
, B(B)
{
const auto Pow = static_cast<int>(std::pow(A, B));
this->A += Pow;
this->B += Pow;
}
};
public: // Specials
X(
const Init& Init
)
: A(Init.A)
, B(Init.B)
{};
X(
const int & A,
const int & B
)
: X(Init(
A,
B
))
{};
};
struct Init
,它扮演过去版本的X
角色。X
成员const
,同时保持Init
成员非const
。Init
。const
成员变量从Init
移动到X
并使它们成为const
。
请注意,没有std::move
,因为int
是TriviallyCopyable。但是,我的解决方案似乎过于复杂。任何帮助,将不胜感激。
X
成员变量,用于存储公共代码结果(即std::pow
)。X
类之外添加另一个间接层(例如,为X
引入基类)。解决方案可以使用比C ++ 11更新的C ++版本。
使用delegating constructor是这种情况的一个很好的选择。
class X
{
public: // Members
/// A ^ B + A
const int A;
/// A ^ B + B
const int B;
public:
X(int a, int b) : X(a, b, func1(a, b)) {}
private:
X(int a, int b, int c) : A(func2(a, b, c)), B(func3(a, b, c)) {}
static int func1(int a, int b) { return std::pow(a,b); }
static int func2(int a, int b, int c) { return (a + c); }
static int func3(int a, int b, int c) { return (b + c); }
};
func1
,func2
和func3
中的逻辑/计算可以根据需要简单或复杂。
您可以使用工厂功能解决此问题。你将X
的构造函数设为private,然后使用friend / static函数来获取X
的对象。然后你可以在函数体中执行复杂的代码,然后将这些值传递给X的构造函数。这看起来像
class X
{
public:
const int A;
const int B;
friend X make_X(int a, int b)
{
// do complex stuff
return X(complex_result1, complex_result2);
}
// or
static X make(int a, int b)
{
// do complex stuff
return X(complex_result1, complex_result2);
}
private:
X(const int A, const int B) : A(A), B(B) {}
};
并将被用作
X foo = make_x(a, b);
//or
X foo = X::make(a, b);