如何在A类内初始化指针类B类foo?我是C++的新手。
Header.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;
}发布于 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:
#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;
}
}
#endifSource.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;
}
};
}
#endifSource.cpp
#include "Header.h"
int main()
{
Core::A *a = new Core::A(10);
//...
delete a;
return 0;
}发布于 2019-04-11 03:08:07
如何在A类内初始化指针类B foo?
备选案文1
使用假设值构造一个B<Left>。
class A
{
public:
B<Left> *foo = new B<Left>(0);
};选项2
添加A的构造函数,该构造函数接受可用于构造B<Left>的int。
class A
{
public:
A(int i) : foo(new B<Left>(i)) {}
B<Left> *foo;
};警告语
在深入使用类中对象的指针之前,请考虑以下几点:
shared_ptr和unique_ptr。https://stackoverflow.com/questions/55624001
复制相似问题