c++11 - 在没有初始化的情况下委托构造函数
问题描述
我正在尝试在没有初始化的情况下实现委托构造函数。这是因为我需要通过函数调用获得的适当值。如何在不重复代码的情况下编写正确的代码?
class foo
{
private:
// Something
public:
foo() = delete;
foo(double a, double b, double c)
{
// Something
}
foo(int n)
{
double a, b, c;
// a, b, c passed by reference and appropriate value is obtained here.
function_call(n, a, b, c);
// construct this object as if the call is foo(a, b, c) now
foo(a, b, c); // ??? Does this work?
}
};
解决方案
foo(a, b, c); // ??? Does this work?
不,它不起作用。它创建了一个临时对象,并且无法初始化当前对象的成员变量。
我的建议:
更改function_call
为返回 astd::tuple<double, double, double>
而不是更新通过引用传递的对象的值。
然后,您可以使用:
class foo
{
private:
foo(std::tuple<double, double, double> const& t) : foo(std::get<0>(t), std::get<1>(t), std::get<2>(t)) {}
public:
foo() = delete;
foo(double a, double b, double c)
{
// Something
}
foo(int n) : foo(function_call(n)) {}
};
您也可以将std::array<double, 3>
其用作构造函数的返回值function_call
并相应地更新构造函数。
foo(std::array<double, 3> const& arr) : foo(arr[0], arr[1], arr[2]) {}
推荐阅读
- objective-c - 自动释放池,Objective-c 与 C++ 正确使用多种语言
- regex - 如何获取字符串不以某些子字符串开头
- php - 我收到此错误:1045error_access denied for "myuser"@myhostaddress(使用密码:是)
- c# - 具有复杂模型映射的 Linq 查询
- wordpress - 自定义分类术语未按顺序打印
- java - 通过反射调用私有静态方法
- excel - 检索所有包含分号的查询
- vue.js - 从多个子组件获取数据到父组件
- c# - 方法参数中的那些词是什么?
- c++ - 如何通过比较其他成员从 QStringList 中删除元素