-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変数の型は( childBoost ::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'
};

テスト.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);
}

メイン.cpp

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);

yourstringが構築される理由は、デフォルトのコンストラクター (空の文字列) を提供しているのに対し、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 に答える