声明用户定义类型的变量以供以后初始化



我想创建一个名为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。

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

Main.cpp

int main()
{
    Test test1;
    test1.SomeFunction();
    cin.get(); // pause
    return 0;
}

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

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


如何才能正确地完成?

作为错误状态,'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();
}

最新更新