C++ c++;初始化模板类构造函数
如何在类A内初始化指针类BC++ c++;初始化模板类构造函数,c++,C++,如何在类A内初始化指针类Bfoo?我是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 {
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;
};
}
名称空间核心
{
枚举类型
{
左,右
};
模板
B类
{
公众:
B(国际一级);
私人:
类型dir;
int b=12;
};
甲级
{
公众:
B*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;
}
#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;
}
#include "Header.h"
int main()
{
Core::A *a = new Core::A(10);
//...
delete a;
return 0;
}
名称空间核心
{
模板
B::B(int i)
{
dir=t;
b=i;
}
}
int main()
{
Core::A*A=新Core::A;
a->foo=新核心::B(10);
返回0;
}
Source.cpp
需要一个#include“Header.h”
语句,Header.h
需要一个Header保护
此外,还需要将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
#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
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;
}
#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;
}
#include "Header.h"
int main()
{
Core::A *a = new Core::A(10);
//...
delete a;
return 0;
}
如何在类A中初始化指针类B foo
选择1
用假定值构造aB
class A
{
public:
B<Left> *foo = new B<Left>(0);
};
警告
在对类中的对象使用指针之前,请考虑以下内容:
共享的
和唯一的