简体   繁体   English

调用没有“ new”的成员变量的构造函数

[英]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.

相关问题 从构造函数内部-有条件地调用成员变量的构造函数重载 - From within a constructor - conditionally call constructor overloads for member variable 我可以在构造函数调用之前设置成员变量吗? - Can I set a member variable before constructor call? 调用成员对象的构造函数 - Call constructor of member object 不使用std :: forward如何调用成员变量的move构造函数? - How is the move constructor of member variable invoked without using std::forward? 打印出未初始化的成员变量。 有无默认构造函数 - Printing out uninitialized member variable. With and without default constructor 如何在 C++ 的类的默认构造函数中调用成员 object 变量的参数化构造函数? - How to call parameterized constructor of member object variable in a class' default constructor in C++? 您如何在不定义变量的地方调用c ++构造函数而不调用new? - How can you call a c++ constructor somewhere other than where you define a variable without calling new? 在复制构造函数定义中调用成员构造函数 - Call member constructor in copy constructor definition C ++,是否可以直接调用构造函数,而不需要新的? - C++, is it possible to call a constructor directly, without new? 成员变量需要构造函数的参数 - Member variable needs parameters for constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM