首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c++初始化模板类构造函数

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

Stack Overflow用户
提问于 2019-04-11 02:54:54
回答 2查看 5.8K关注 0票数 1

如何在A类内初始化指针类B类foo?我是C++的新手。

Header.h

代码语言:javascript
运行
复制
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;
    };
}

Source.cpp

代码语言:javascript
运行
复制
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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-11 03:06:13

Source.cpp需要一个#include "Header.h"语句,Header.h需要一个头部保护。

另外,您需要将B构造函数的实现移到头文件中。参见Why can templates only be implemented in the header file?

试试这个:

头H:

代码语言:javascript
运行
复制
#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

Source.cpp

代码语言:javascript
运行
复制
#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:

代码语言:javascript
运行
复制
#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

Source.cpp

代码语言:javascript
运行
复制
#include "Header.h"

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

Stack Overflow用户

发布于 2019-04-11 03:08:07

如何在A类内初始化指针类B foo?

备选案文1

使用假设值构造一个B<Left>

代码语言:javascript
运行
复制
class A
{
   public:
    B<Left> *foo = new B<Left>(0);
};

选项2

添加A的构造函数,该构造函数接受可用于构造B<Left>int

代码语言:javascript
运行
复制
class A
{
   public:
      A(int i) : foo(new B<Left>(i)) {}
    B<Left> *foo;
};

警告语

在深入使用类中对象的指针之前,请考虑以下几点:

  1. What is The Rule of Three?
  2. https://en.cppreference.com/w/cpp/memory,特别是shared_ptrunique_ptr
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55624001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档