簡體   English   中英

C ++常量結構成員初始化

[英]C++ Constant structure member initialization

struct timespec有一個常量的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,來自/ 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個提供

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM