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;
};
}
资料来源.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>
int
的 A
构造函数。
class A
{
public:
A(int i) : foo(new B<Left>(i)) {}
B<Left> *foo;
};
注意事项
在过多地使用指向类中的对象的指针之前,请考虑以下事项:
- 什么是三法则?
- https://en.cppreference.com/w/cpp/memory,特别是
shared_ptr
和unique_ptr
.
相关文章:
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 类内初始化与构造函数初始化列表的顺序
- 通过 C++ 中的重载构造函数初始化未知类型的变量
- 使用复制构造函数初始化 new[]
- 如何从子类的构造函数初始化父类的私有成员
- 在构造函数初始化列表中使用 std::variant
- 使用构造函数初始化结构还是在之后设置其值更好?
- C++ 没有匹配的构造函数初始化 []
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- 使用所述填充构造函数初始化向量中的向量
- 如何同时创建一个具有两个或多个构造函数初始化的对象
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 这是使用构造函数初始化数组对象的最佳方法吗?
- 内置类型的构造函数初始化
- 构造函数初始化和对象损坏