【问题标题】:Thread Program in visual C++/CLI giving errorsVisual C++/CLI 中的线程程序给出错误
【发布时间】:2013-07-11 12:05:05
【问题描述】:

我正在尝试按照http://www.drdobbs.com/cpp/ccli-threading-part-i/184402018 的教程在 Visual c++ 中使用 winform 进行线程编程。我打开了一个 win32 控制台项目,并在其中添加了一个空的 cpp 文件,我在其中放置了如下代码:

    using namespace System;
    using namespace System::Threading;

    public class ThreadX{

        int loopStart;
        int loopEnd;
        int dispFrequency;

        public:


        ThreadX(int startValue, int endValue, int frequency)
        {
            loopStart = startValue;
            loopEnd = endValue;
            dispFrequency = frequency;
        }

        void ThreadEntryPoint()
        {
            String^ threadName = Thread::CurrentThread->Name;

            for (int i = loopStart; i <= loopEnd; ++i)
            {
                if ( i % dispFrequency == 0)
                {
                    Console::WriteLine("{0} : i = {1,10}", threadName, i);
                }
            }
            Console::WriteLine("{0} thread terminating", threadName);
        }
};

int main()
{
    ThreadX o1 = gcnew ThreadX(0, 1000000,200000);
    Thread^ t1 = gcnew Thread(gcnew ThreadStart(o1, &ThreadX::ThreadEntryPoint));
    t1->Name = "t1";

    ThreadX o2 = gcnew ThreadX(-1000000, 0, 200000);
    Thread^ t2 = gcnew Thread(gcnew ThreadStart(o2, &ThreadX::ThreadEntryPoint));
    t1->Name = "t2";

    t1->Start();
    t2->Start();
    Console::WriteLine("Primary Thread Terminating");
}

但是这给了我错误,例如:

  1. 错误 C2726:“gcnew”只能用于创建具有 托管类型
  2. 错误 C2440:“正在初始化”:不能 从 'ThreadX *' 转换为 'ThreadX' 没有构造函数可以接受 源类型或构造函数重载决议不明确
  3. 错误 C3364:“System::Threading::ThreadStart”:委托构造函数的参数无效;委托目标需要是 指向成员函数的指针

【问题讨论】:

    标签: multithreading visual-studio-2010 visual-c++ c++-cli


    【解决方案1】:

    您正在混合 C++ 和 C++/CLI,这是另一回事。替换

    public class ThreadX
    

    public ref class ThreadX
    

    【讨论】:

    • 这正是清单中的代码所说的 - 清楚地复制和粘贴错误!
    • @doc:请删除以下语句,以防止 C++ 和 C++/CLI 混合:#include &lt;iostream&gt; using namespace std;
    • @我?我没有添加它们@user2572521 做了 - 灾难性的复制和粘贴并制作了额外的东西错误:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2011-05-27
    • 1970-01-01
    相关资源
    最近更新 更多