当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Doing necessary work before member initialization in constructor

问题描述:

I've got a design question concerning classes and their constructors in C++. I'm coming from several years of Java experience. In Java, I would do things like this: I've got a class to manage an SQLite DB as a storage backend. In the constructor of this class, I would hand over the path to the applications data directory as a parameter. Then, I would look for the database file, instatiate a connection, and for example load the most current entry of a table for the purpose of caching.

My Problem now is how to do this in C++. My main problem here is that when execution reaches the first statement of the constructor, all class members were already initialized, either implicitly or explicitly.

My question now is: If I had some computations to do on the constructor parameters before using them to initialize the class members, how would I do that in C++?

I've already found that I can simply use assignment to the members in the constructors, but I've also read you should not do that, because it would mean that the members are first initialized with their default constructors, and then initialized again.

What is the canonical way when you have some computation to do (e.g. loading and parsing a configuration file) before class members can be initialized? I would prefer to simply give a path to the constructor, and then do the loading and parsing an member initialization with the loaded values inside the constructor.

网友答案:

Put the computation part in separate function:

class C {
  std::string x;
  int y;
  C(int xarg, int yarg);
};

std::string computeX(int xarg, int yarg) {
    ...
  return result;
}

C::C(int xarg, int yarg) : x(computeX(xarg, yarg)), y(yarg) {}

As the "initialisation" function you may use a global function, a function defined locally in the source file (e.g. in unnamed namespace), or even invoke a lambda defined in place. You can also use a static member function - also if it is private - or a member function of one of the arguments.

分享给朋友:
您可能感兴趣的文章:
随机阅读: