簡體   English   中英

是否可以在.cpp中初始化/調用CTOR?

[英]Is there a way to init/call CTOR in the .cpp?

我在.h有這些指針聲明對象:

ILFO *pLFOPianoRoll1, *pLFOPianoRoll2, *pLFOPianoRoll3;

我在.cpp使用以下命令初始化它:

pLFOPianoRoll1 = new ILFO(this, 8, 423, kParamIDPianoRollLFO1, 0);
pLFOPianoRoll2 = new ILFO(this, 8, 542, kParamIDPianoRollLFO1, 1);
pLFOPianoRoll3 = new ILFO(this, 8, 661, kParamIDPianoRollLFO1, 2);

但是我想在這里避免使用指針(我了解到“如果您不需要它們,就不要使用它們”),而只需使用變量/類(由於稍后會手動管理內存)。

但是,如何在.h中ILFO mLFOPianoRoll1對象的變量(例如ILFO mLFOPianoRoll1 ),然后在.cpp上調用CTOR呢?

為了簡單地聲明變量,請使用extern關鍵字:

extern ILFO obj; //just declaration, no constructor is called.

在.cpp文件中

ILFO obj(blah, blah, blah); //definition

當然,這是在談論名稱空間范圍(包括全局)變量時。 如果您在談論類成員,那么您必須知道,直到類的構造函數才調用成員的構造函數。 您可以在構造函數初始化列表中將參數傳遞給構造函數

您可以為此使用初始化列表。

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
    A(int a_) : a(a_) { }

    void print() 
    {
        std::cout << "A: " << a << std::endl;
    }

    int a;
};

class B
{
public:
    B() : a(1), a2(3) {}
    A a;
    A a2;
};

int main() {
    B bObj;
    bObj.a.print();
    bObj.a2.print();
   return 0;
}

https://ideone.com/C7Vx1X

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM