Объявление переменной пользовательского типа для последующей инициализации

Я хочу создать глобальную переменную под названием process не назначая ему ничего в первый момент. Позже я создам новый процесс в операционной системе и назначу его этой переменной.

Это можно сделать в C # примерно так:

class TestCS
{
// creating a variable
private System.Diagnostics.Process process;

private void SomeMethod()
{
// assigning a newly spawned process to it
process = Process.Start("file.exe", "-argument");
process.WaitForInputIdle();
}
}

Я написал код ниже, чтобы выполнить то же самое с C ++. process переменная имеет тип child (от Повысьте :: Процесс v0.31). #включает в себя опущены для простоты.

Test.hpp

class Test
{
public:
void SomeFunction();
private:
std::string testString; // declaring a test string

static const std::string program_name;
static const std::vector<std::string> program_args;
boost::process::child process;  // attempting to declare a variable of type 'boost::process::child'
};

test.cpp

void Test::SomeFunction()
{
testString = "abc"; // I can successfully define the test variable on this line
std::cout << testString;

boost::process::context ctxt;

// the same goes for the next two variables
const std::string program_name = "startme.exe";
const std::vector<std::string> program_args = {"/test"};

// and I want to define the process variable here as well...
process = boost::process::launch(program_name, program_args, ctxt);
}

main.cpp

int main()
{
Test test1;
test1.SomeFunction();

cin.get(); // pause
return 0;
}

Тем не менее, он возвращает следующую ошибку для test.cpp:

ошибка C2512: ‘boost :: process :: child’: нет подходящего конструктора по умолчанию

Как это можно сделать правильно?

-1

Решение

Как говорится в ошибке, 'boost::process::child' no appropriate default constructor available, Это означает, что child Объект должен быть построен с помощью конструктора, который принимает аргументы.

Возьмите следующий пример класса

class Foo
{
Foo(); // This is the _default_ constructor.
Foo(int i); // This is another constructor.
};

Foo f; // The `Foo();` constructor will be used _by default_.

Если мы изменим этот класс на следующий:

class Foo
{
Foo(int i); // This is the constructor, there is no default constructor declared.
};

Foo f; // This is invalid.
Foo f(1); // This is fine, as it satisfies arguments for `Foo(int i);

Причина ваша string построен потому, что он предоставляет конструктор по умолчанию (который является пустой строкой), в то время как process::child класс нет.

Поэтому вам нужно инициализировать вас process::child объект, когда он построен. Так как это часть TestClass (а не указатель или ссылка), он должен быть построен когда TestClass объект построен.

Test::Test()
: process() // Initialize the member here, with whatever args.
{
SomeFunction();
}

Или же…

class Test
{
// Make it a pointer.
boost::process::child* pProcess;
};

Test::Test()
{
pProcess = new boost::process::child(); // And allocate it whenever you want.
SomeFunction();
}
2

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector