Initializing a Global Variable Class

Apologies for such a basic question, but I can't figure it out. I know that you can initialize a class as follows:

QFile file("C:\\example");

But how would you initialize it from a global variable? For instance:

QFile file; //QFile class

int main()
{
    file = ?? //need to initialize 'file' with the QFile class
}
+5
source share
4 answers

1. Direct answer

If the class can be assigned / copied, you can simply write

QFile file; //QFile class

int main()
{
    file = QFile("C:\\example");
}

2. Use indirect actions

If not, you will have to resort to other parameters:

QFile* file = 0;

int main()
{
    file = new QFile("C:\\example");

    //
    delete file;
}

Or use the boost::optional<QFile>, std::shared_ptr<QFile>, boost::scoped_ptr<QFile>etc.

3. Use singleton patterns:

Because of Fiasco's Static Initialization, you can write a function like this:

static QFile& getFile()
{ 
    static QFile s_file("C:\\example"); // initialized once due to being static
    return s_file;
}

++ 11 โ€‹โ€‹- ( ++ 0x n3242, ยง6.7:)

enter image description here

+10

:

// file.cpp

QFile file("C:\\example");

int main()
{
  // use `file`
}

main() ( ).

+3
#include <iostream>
struct QFile
{
    char const* name;
    QFile(char const* name) : name(name) {}
};

QFile file("test.dat"); // global object

int main()
{
    std::cout << file.name << std::endl;
}

, :

,

. , .

+1

, - .

, , , .

QFile file; //class object

int main()
{
    file = QFile("C:\\example"); //create a temporary object and copy it to `file`
}

,

QFile *file;

int main()
{
    file = new QFile("C:\\example");
}

Please note: if you use this global variable only inside the file, you can make it a variable static. Then it is limited to a file. This way you can minimize bad global variables.

+1
source

All Articles