让我们介绍这个简单的例子:
#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
。
如何做到这一点而不重复复杂的初始化( ie 避免两次调用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
是TriviallyCopyable,因此没有int
。但是,我的解决方案似乎过于复杂。任何帮助将不胜感激。
X
成员变量,该变量将存储通用代码结果( ie std::pow
)。X
类之外添加另一个间接级别( eg 为X
引入基类)。解决方案可以使用比C ++ 11更新的C ++版本。
答案 0 :(得分:5)
在这种情况下,使用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
中的逻辑/计算可以根据需要简单或复杂。
答案 1 :(得分:3)
您可以通过使用工厂函数来解决此问题。您将X
的构造函数设为私有,然后使用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);