【问题标题】:function return with custom defined managed class type具有自定义托管类类型的函数返回
【发布时间】:2017-03-26 08:10:22
【问题描述】:

我在使用 C++/CLI 时遇到问题。 我定义了一个名为 Person 的类,它是一个带有获取和集合的简单类: #pragma 一次 使用命名空间系统;

namespace CLI
{
    public ref class Person
    {
    public:
        Person();
        // gets and sets
    private:
        String^ name;
        int age;
    };
}

然后我用 person 定义了一个矩阵类: #pragma 一次 #include "人.h" 使用命名空间系统;

namespace CLI
{
    // Next is the managed wrapper of Logic:
    public ref class Matrix
    {
    public:
        Matrix();
        Person^ getPerson(int i, int j)
        {
            return paa[i][j]; // no problem
        }
        void Destroy();
    private:
        array<array<Person^>^>^ paa;
    };
}

很奇怪,如果我把getPerson()函数移到.cpp,会报错。

这是有错误的 Matrix.h 和 Matrix.cpp:

// Matrix.h
#pragma once
#include "Person.h"
using namespace System;

namespace CLI
{
    public ref class Matrix
    {
    public:
        Matrix();
        Person^ getPerson(int i, int j);
        void Destroy();
    private:
        array<array<Person^>^>^ paa;
    };
}


// Matrix.cpp
#include "Matrix.h"

CLI::Matrix::Matrix()
{
    // init the matrix
}

Person^ CLI::Matrix::getPerson(int i, int j) // errors here
{
    return paa[i][j];
}

其中一个错误是“未定义标识符:Person”,这个错误指向函数返回类型。我试着写“Person^ p = gcnew Person;”在函数体中,没有错误。 另一个错误是“The function definition is not compatible with the one in .h file”(我不是用英文版的VS,我翻译的消息,可能不太准确。)

如果我更改任何非自定义的返回类型,例如 int、String^,就可以了。

如果需要更多信息,请告诉我。

【问题讨论】:

  • 请告诉我们导致错误的代码,而不是没有的代码。
  • @DavidYaw 我编辑了,我给出的代码有错误。

标签: c++ c++-cli clr


【解决方案1】:
Person^ CLI::Matrix::getPerson(int i, int j)

Person 类是在 CLI 命名空间中定义的,但您在这里没有引用该命名空间。

您没有在头文件中收到错误消息,因为声明包含在 namespace CLI { } 块中,而 cpp 文件没有。

要解决此问题,我建议您将 cpp 文件中的所有代码包含在 namespace CLI { } 块内,并从各种声明中删除 CLI::。我认为这看起来比其他解决方案更简洁,即完全限定返回类型 (CLI::Person^)。

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 2021-03-18
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多