提问者:小点点

C++常量结构成员初始化


我的类中有一个常量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个


共3个答案

匿名用户

在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})

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|常量|结构|成员|初始化)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?