[英]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?
使用假定值构造一个B<Left>
。
class A
{
public:
B<Left> *foo = new B<Left>(0);
};
添加A
的构造函数,该构造函数接受可用于构造B<Left>
的int
。
class A
{
public:
A(int i) : foo(new B<Left>(i)) {}
B<Left> *foo;
};
在深入使用指向类中对象的指针之前,请考虑以下事项:
shared_ptr
和unique_ptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.