-1

我想创建一个名为的全局变量,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)。为简单起见,省略了#include 。

测试.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'
};

测试.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);
}

主文件

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

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

但是,它为Test.cpp返回以下错误:

错误 C2512:'boost::process::child':没有合适的默认构造函数可用


如何正确完成?

4

1 回答 1

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();
}
于 2014-10-13T22:11:49.360 回答