[英]Call constructor of a member variable without 'new'
I want to call the constructor of a member m_foo
of Class A
in the constructor of Class A
. 我想打电话给会员的构造
m_foo
类的A
在类的构造函数A
。 Is it nessecary to call it with m_foo = new Foo()
? 用
m_foo = new Foo()
调用它是否必要? Or can I call it without putting it on the Heap? 还是可以不将其放在堆上就调用它? I want to pass a pointer to an array of 256 Byte, so that the Foo object fills its member array with the data the pointer points to.
我想将指针传递给256字节的数组,以便Foo对象用指针指向的数据填充其成员数组。 But how would I call a contructor of a member variable that I declare in the headerfile?
但是,如何调用在头文件中声明的成员变量的构造函数?
A.hpp 丙型肝炎
class A{
public
A();
private:
Foo m_foo;
};
A.cpp 丙型肝炎
A::A()
{
//How to call constructor of class Foo here?
}
Foo.hpp Foo.hpp
class Foo()
{
Foo(char* p)
{
memcpy(m_Array, p, sizeof(m_Array)/sizeof(m_Array[0]));
}
private:
char m_Array[256];
};
Use the member initialization list for the A
constructor : 将成员初始化列表用于
A
构造函数:
A::A() : m_foo(...)
{
}
You can get the char*
required to build m_foo
from : 您可以从获取构建
m_foo
所需的char*
:
A
constructor : A
构造函数:
A::A(char* p) : m_foo(p) {}
Or another function : 或其他功能:
A::A() : m_foo(GetBuffer()) {}
If you don't mind passing the pointer to A's constructor, this may be what you want: 如果您不介意将指针传递给A的构造函数,则可能是您想要的:
class A
{
public:
A(const char* p);
private:
Foo m_foo;
};
A::A(const char* p) : m_foo(p) // <- calls Foo's ctor here
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.