我班上有一个不变的 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)'源的匹配函数 . 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,from / 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:注意:念珠菌te期望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个提供
3 回答
在C 11中,您可以在构造函数的初始化列表中初始化聚合成员:
在旧版本的语言中,您需要一个工厂函数:
使用带辅助函数的初始化列表:
使用初始化列表
如果要使用撑杆初始化结构,请使用它们