C++ 初始化模板类构造函数

c++ initialize template class constructor

本文关键字:构造函数 初始化 C++      更新时间:2023-10-16

如何在类 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;
    };
}

资料来源.cpp

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

资料来源.cpp

#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

资料来源.cpp

#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

添加接受可用于构造B<Left> intA 构造函数。

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.