[英]c++ initialize template class constructor
How do I initialize pointer class B foo
inside class A?如何在类 A 中初始化指针类 B
foo
? I am new to C++.我是 C++ 的新手。
Header.h头文件.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;
};
}
Source.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
needs a #include "Header.h"
statement, and Header.h
needs a header guard. Source.cpp
需要一个#include "Header.h"
语句,而Header.h
需要一个标题保护。
Also, you need to move the implemention of B
's constructor into the header file.此外,您需要将
B
的构造函数的实现移动到头文件中。 See Why can templates only be implemented in the header file?请参阅为什么模板只能在头文件中实现? .
.
Try this:尝试这个:
Header.h:标题.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
Source.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;
}
I would suggest taking it a step further by inlining B
's constructor and giving A
a constructor to initialize foo
:我建议更进一步,通过内联
B
的构造函数并给A
一个构造函数来初始化foo
:
Header.h:标题.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
Source.cpp源文件
#include "Header.h"
int main()
{
Core::A *a = new Core::A(10);
//...
delete a;
return 0;
}
How do I initialize pointer class B foo inside class A?
如何在类 A 中初始化指针类 B foo?
Construct a B<Left>
with an assumed value.使用假定值构造一个
B<Left>
。
class A
{
public:
B<Left> *foo = new B<Left>(0);
};
Add a constructor of A
that accepts an int
that can be used to construct a B<Left>
.添加
A
的构造函数,该构造函数接受可用于构造B<Left>
的int
。
class A
{
public:
A(int i) : foo(new B<Left>(i)) {}
B<Left> *foo;
};
Before you down too far into using pointers to objects in your classes, consider the following:在深入使用指向类中对象的指针之前,请考虑以下事项:
shared_ptr
and unique_ptr
. shared_ptr
和unique_ptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.