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

斯尔詹·M。

如何foo在类 A 中初始化指针类 B 我是 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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++初始化构造函数初始化器列表中的模板数组

C ++构造函数如何初始化其类的对象?

在类构造函数中初始化const向量(C ++)

C ++类模板初始化问题

c ++模板类,初始化()与{}

为什么派生类的构造函数要在C ++中初始化虚拟基类?

C++在初始化类实例时隐式调用类成员的构造函数

在C ++中没有匹配的构造函数来初始化可变参数模板

C ++中的初始化程序列表和类初始化。我有无参数构造函数,但仍必须使用初始化列表?

C ++ 11:带“ = {}”的类内初始化不适用于显式构造函数

如何使用已删除的副本构造函数初始化类数组(C ++ 11)

C ++ 11:默认的默认构造函数可以导致部分初始化的类吗?

在没有构造函数的情况下初始化const c ++类

如何在类的构造函数中初始化对象的2D向量?(C ++)

类C,构造函数和统一初始化之间有什么区别?

C ++类:在没有构造函数重载的情况下初始化属性

C ++的类变量可以在没有Java构造函数的情况下初始化吗?

在C ++中的类构造函数中进行列表初始化

构造函数体中的 C++ 类 const 成员初始化

如何在C ++中使用构造函数(只是构造函数)在类中初始化大型私有数组?

C ++:具有任意数量的初始化参数的模板类/函数

C++ 通过分配其他构造函数初始化的类成员来初始化类成员是一个坏主意吗?

在C ++中的自定义类的构造函数中初始化没有参数的静态const类成员

在C ++中,类是否可以包含指向构造函数中初始化的同一类的指针?

c++ - 构造函数不能用于初始化

c ++构造函数成员初始化:传递参数

C++ - 构造函数中的 std::vector 初始化

C ++在构造函数中初始化对象(多态)

C ++没有匹配的构造函数的[]初始化