我想创建一个名为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
(来自Boost::Process v0.31)。为简单起见,省略了 #includes 。
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':没有合适的默认构造函数
如何正确完成?
答案 0 :(得分:2)
如错误所述,'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();
}