我的类中有一个常量struct timespec
成员。我该怎么初始化它?
我得到的唯一疯狂的想法是派生我自己的timespec
并给它一个构造函数。
多谢了!
#include <iostream>
class Foo
{
private:
const timespec bar;
public:
Foo ( void ) : bar ( 1 , 1 )
{
}
};
int main() {
Foo foo;
return 0;
}
编译已完成,但出现错误:source.cpp:在构造函数“foo::foo()”中:source.cpp:9:36:错误:没有匹配函数用于调用“timespec::timespec(int,int)”source.cpp:9:36:注意:候选项包括:在文件中,从sched.h:34:0,从pthread.h:25,从/usr/lib/gcc/i686-pc-linux-gnu/4.7.2/../../../include/C++/4.7.2/i686-pc-linux-gnu/bits/gthr-default.h:41,从需要0个参数,但提供了2个时间。H:120:8:注意:constexpr Timespec::Timespec(const Timespec和)Time.H:120:8:注意:候选人需要1个参数,提供了2个时间.H:120:8:注意:constexpr TimeSpec::TimeSpec(TimeSpec&&)Time.h:120:8:注意:候选人需要1个参数,提供2个
在C++11中,您可以初始化构造函数初始值列表中的聚合成员:
Foo() : bar{1,1} {}
在该语言的旧版本中,您需要一个工厂函数:
Foo() : bar(make_bar()) {}
static timespec make_bar() {timespec bar = {1,1}; return bar;}
使用带有帮助器函数的初始化列表:
#include <iostream>
#include <time.h>
#include <stdexcept>
class Foo
{
private:
const timespec bar;
public:
Foo ( void ) : bar ( build_a_timespec() )
{
}
timespec build_a_timespec() {
timespec t;
if(clock_gettime(CLOCK_REALTIME, &t)) {
throw std::runtime_error("clock_gettime");
}
return t;
}
};
int main() {
Foo foo;
return 0;
}
使用初始化列表
class Foo
{
private:
const timespec bar;
public:
Foo ( void ) :
bar(100)
{
}
};
如果要使用护括号初始化结构,请使用它们
Foo ( void ) : bar({1, 2})