I want to call another constructor of the same class depending on the execution condition. The constructor uses different initialization lists (a bunch of things after :), so I can not handle the condition inside the constructor.
:
For instance:
#include <vector> int main() { bool condition = true; if (condition) { // The object in the actual code is not a std::vector. std::vector<int> s(100, 1); } else { std::vector<int> s(10); } // Error: s was not declared in this scope s[0] = 1; }
I assume I can use a pointer.
#include <vector> int main() { bool condition = true; std::vector<int>* ptr_s; if (condition) { // The object in the actual code is not a std::vector. ptr_s = new std::vector<int>(100, 1); } else { ptr_s = new std::vector<int>(10); } (*ptr_s)[0] = 1; delete ptr_s; }
Is there a better way if I haven't written a move constructor for my class?
, , ( ), , initialize, , .
initialize
int main() { bool condition = true; SomeClass object; if (condition) { object.initialize(some params 1) } else { object.initialize(some params 2) } }
, - , , "dummy", . DoNothing :
DoNothing
SomeClass object(DoNothing())
-
std::vector<int> ptr_s; if (condition) { ptr_s.resize(100); } else { ptr_s.resize(10); }
?
Source: https://habr.com/ru/post/1671065/More articles:Проблемы с настройками проекта Cocoapods - iosDjango pipes for asynchronous periodic tasks - pythonКак я могу выполнить условие ИЛИ в политике корзины S3? - jsonAssigning a vector to one element - c ++smart any () function to check if at least n elements are True? - pythonXpath includes starting up - out of work - xpathoracle filter on plan explanation sections - oracleHow to make tslint monitor changes in a specific folder? - typescriptКак запустить tslint непрерывно с помощью webpack или vs code во время разработки - angularКак изменяется размер партии в разное время прогнозирования? - deep-learningAll Articles