Kol*_*nya 9 c++ constructor struct const constants
struct timespec我班上有一名成员.我该如何初始化它?
我得到的唯一疯狂的想法是派生我自己的timespec并给它一个构造函数.
非常感谢!
#include <iostream>
class Foo
{
private:
const timespec bar;
public:
Foo ( void ) : bar ( 1 , 1 )
{
}
};
int main() {
Foo foo;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译完成时出现错误: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,来自/ usr/lib/gcc/i686-pc-linux -gnu/4.7.2 /../../../../ include/c ++/4.7.2/i686-pc-linux-gnu/bits/gthr.h:150,来自/ usr/lib/gcc /i686-pc-linux-gnu/4.7.2/../../../../include/c++/4.7.2/ext/atomicity.h:34,来自/ usr/lib/gcc/i686 -pc-linux-gnu/4.7.2 /../../../../ include/c ++/4.7.2/bits/ios_base.h:41,来自/ usr/lib/gcc/i686-pc -linux-gnu/4.7.2 /../../../../ include/c ++/4.7.2/ios:43,来自/usr/lib/gcc/i686-pc-linux-gnu/4.7 .2 /../../../../ include/c ++/4.7.2/ostream:40,来自/usr/lib/gcc/i686-pc-linux-gnu/4.7.2/../ ../../../include/c++/4.7.2/iostream:40,来自source.cpp:1:time.h:120:8:注意:timespec :: timespec()time.h:120: 8:注意:候选人 期望0个参数,2提供time.h:120:8:注意:constexpr timespec :: timespec(const timespec&)time.h:120:8:注意:候选者需要1个参数,2个提供time.h:120:8:注意:constexpr timespec :: timespec(timespec &&)time.h:120:8:注意:候选人需要1个参数,2个提供
Mik*_*our 11
在C++ 11中,您可以在构造函数的初始化列表中初始化聚合成员:
Foo() : bar{1,1} {}
Run Code Online (Sandbox Code Playgroud)
在旧版本的语言中,您需要一个工厂函数:
Foo() : bar(make_bar()) {}
static timespec make_bar() {timespec bar = {1,1}; return bar;}
Run Code Online (Sandbox Code Playgroud)