簡體   English   中英

c ++初始化模板類構造函數

[英]c++ initialize template class constructor

如何在類 A 中初始化指針類 B foo 我是 C++ 的新手。

頭文件.h

namespace Core
{
    enum type
    {
        Left, Right
    };

    template<type t>
    class B
    {
    public:
        B(int i);
    private:
        type dir;
        int b = 12;
    };

    class A
    {
    public:
        B<Left> *foo;
    };
}

源文件

namespace Core
{
    template<type t>
    B<t>::B(int i)
    {
        dir = t;
        b = i;
    }
}

int main()
{
    Core::A *a = new Core::A;
    a->foo = new Core::B<Core::Left>(10);

    return 0;
}

Source.cpp需要一個#include "Header.h"語句,而Header.h需要一個標題保護。

此外,您需要將B的構造函數的實現移動到頭文件中。 請參閱為什么模板只能在頭文件中實現? .

嘗試這個:

標題.h:

#ifndef HeaderH
#define HeaderH

namespace Core
{
    enum type
    {
        Left, Right
    };

    template<type t>
    class B
    {
    public:
        B(int i);
    private:
        type dir;
        int b = 12;
    };

    class A
    {
    public:
        B<Left> *foo;
    };

    template<type t>
    B<t>::B(int i)
    {
        dir = t;
        b = i;
    }
}

#endif

源文件

#include "Header.h"

int main()
{
    Core::A *a = new Core::A;
    a->foo = new Core::B<Core::Left>(10);
    //...
    delete a->foo;
    delete a;
    return 0;
}

我建議更進一步,通過內聯B的構造函數並給A一個構造函數來初始化foo

標題.h:

#ifndef HeaderH
#define HeaderH

namespace Core
{
    enum type
    {
        Left, Right
    };

    template<type t>
    class B
    {
    public:
        B(int i)
        {
            dir = t;
            b = i;
        }

    private:
        type dir;
        int b = 12;
    };

    class A
    {
    public:
        B<Left> *foo;

        A(int i = 0)
            : foo(new B<Left>(i))
        {
        }

        ~A()
        {
            delete foo;
        }
    };
}

#endif

源文件

#include "Header.h"

int main()
{
    Core::A *a = new Core::A(10);
    //... 
    delete a;
    return 0;
}

如何在類 A 中初始化指針類 B foo?

選項1

使用假定值構造一個B<Left>

class A
{
   public:
    B<Left> *foo = new B<Left>(0);
};

選項 2

添加A的構造函數,該構造函數接受可用於構造B<Left>int

class A
{
   public:
      A(int i) : foo(new B<Left>(i)) {}
    B<Left> *foo;
};

謹慎的話

在深入使用指向類中對象的指針之前,請考慮以下事項:

  1. 三分法則是什么?
  2. https://en.cppreference.com/w/cpp/memory ,特別是shared_ptrunique_ptr

暫無
暫無

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

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