不能调用基类成员函数,因为基类是模板化的。

问题描述 投票:0回答:1

是否有某种限制,如果一个基类是模板化的,我们就不能在派生类中调用它的成员函数?那岂不是违反了从它出发的整个目的?有什么解决方法吗?

下面是我的例子来证明这个问题。

这些类位于类库中

namespace CLRLib {

    class A
    {
    public:

    };

    public ref class SimpleBase
    {
    public:

        void Hello()
        {
            cout << "SimpleBase::Hello() called" << endl;
        }

    };

    public ref class DerivedFromSimple : public SimpleBase
    {
    public:

        void Print()
        {
            cout << "Derived::Print called" << endl;
        }
    };


    template<class T>
    public ref class Base
    {
    public:
        T* m_Instance;

        void Hello()
        {
            cout << "Base::Hello() called" << endl;
        }

        T* GetInstance()
        {
            return m_Instance;
        }

    };

    public ref class Derived : public Base <A>
    {
    public:

        void Print()
        {
            cout << "Derived::Print called" << endl;
        }
    };
}

而这是驱动控制台应用程序。注意,如果它们都在同一个C++CLI项目中,问题就不会发生。

int main(cli::array<System::String ^> ^args)
{
    Derived d;

    d.Print(); // yes
    //d.Hello(); // Doesn't compile, don't recognize the function.

    DerivedFromSimple d2;
    d2.Print();
    d2.Hello(); // Ok now

    return 0;
}

我又可以制作它 只是 如果类是在单独的C++CLI .NET库中,而驱动应用程序是一个单独的C++CLI控制台应用程序。I 不能 调用该配置中的基类方法,因为它们驻留在不同的汇编中?是的,如果它们在同一个汇编中,就没有问题! 颇为奇怪。

错误信息是

错误C2039: 'Hello': 不是CLRLib::Derived的成员。

更新

我确实确认这与base类是模板类有关。我已经更新了上面的代码。当我从一个简单的基类(没有模板)派生时,基类函数是可用的,我可以调用,但如果基类使用模板,则无法访问。

更新2

如果我在派生类成员函数中调用Hello(),那么我也可以在主程序中调用它。但这并不能解决这个问题。

public ref class Derived : public Base <A>
{
public:

    void Print()
    {
        cout << "Derived::Print called" << endl;

        Hello();
    }
};
c++ c++-cli
1个回答
1
投票

你有访问问题。

你可以改一下 protectedpublic:

template<class T>
class Base
{
public:

    void Hello()
    {
        cout << "Base::Hello() called" << endl;
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.