模板类关系

时间:2013-03-25 15:10:19

标签: c++ class templates

template<class Rawr>
class TestContains;

template <class T>
class TestStore//: public TestContains
{
public:
    TestStore(T first, T second, T W, T H)
    {
        x = first;
        y = second;
        Width = W;
        Height = H;

        TestContains<T> a(x, y, Width, Height);

        *b = a;
    }
    ~TestStore() {};


    T x;
    T y;
    T Width;
    T Height;

TestContains<T>* GetRect();

protected:
private:
TestContains<T> *b;
};

CPP

template<class T>
TestContains<T>* TestStore<T>::GetRect()
{
    return &b;
}

测试包含

template<class Rawr>
class TestContains
{
    public:
        TestContains(Rawr first, Rawr second,  Rawr W, Rawr H)
        {
            x = first;
            y = second;
            Width = W;
            Height = H;
        }

        ~TestContains(){};

    template <class T>
    bool Contains(T Mx, T My)
    {
       if (Mx >= x && Mx <= x + Width && My >= y && My <= My + Height)
       return true;

       return false;
    }

Rawr x;
Rawr y;
Rawr Width;
Rawr Height;

///friend?
template<class T>
friend class TestStore;

    protected:
    private:
};

实施

TestStore<int> test(0, 0, 100, 100);

if (test.GetRect().Contains(mouseX, mouseY))
{
    std::cout << "Within 0, 0, 100, 100" << std::endl;
}

无论如何...所以我无法编译,因为我

  

/home/chivos/Desktop/yay/ShoeState.cpp||在成员函数'virtual void ShoeState :: GameLoop(GameEngine *)':   /home/chivos/Desktop/yay/ShoeState.cpp|51| error:请求'test.TestStore :: GetRect with T = int'中的成员'Contains',这是非类型'TestContains *'|   || ===构建完成:1个错误,0个警告=== |

我一直在搞乱这个问题,它开始困扰我了!大声笑,有没有人知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

错误告诉您test.GetRect()返回指针。要通过指向对象的指针访问成员,您应该使用->而不是.

//                ▾▾
if (test.GetRect()->Contains(mouseX, mouseY))
{
    std::cout << "Within 0, 0, 100, 100" << std::endl;
}

答案 1 :(得分:2)

两个问题:sftrabbit在他/她的回答中指出了一个问题。另一种是你试图在GetRect函数中返回指针指针:使用&运算符的地址将使return语句返回指针的地址,即指向指针。

你有一个比编译错误更严重的问题,一个是未定义的行为并且很可能最终导致崩溃:在类TestStore中你有成员变量b这是一个指针。在构造函数中,您指定它指向的内容,但那时它实际上并不指向任何内容,而是覆盖随机内存。

在使用取消引用操作符分配指针之前分配指针,或者根本不使用指针(我的推荐)。

相关问题