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;
};
人民党
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||In member function ‘virtual void ShoeState::GameLoop(GameEngine*)’:| /home/chivos/Desktop/yay/ShoeState.cpp|51|error: request for member ‘Contains’ in ‘test.TestStore::GetRect with T = int’, which is of non-class type ‘TestContains*’| ||=== Build finished: 1 errors, 0 warnings ===|
我已经弄乱了很长时间,它开始困扰我了!大声笑,有人知道我做错了什么吗?
最佳答案
两个问题:一个是sftrabbit在他/她的回答中指出的。另一种是您尝试在 GetRect
函数中返回一个指向指针的指针:使用 address-of &
运算符将使 return 语句返回指针,即指向指针的指针。
你有一个比编译错误更严重的问题,一个未定义的行为并且很可能以崩溃告终:在 TestStore
类中你有成员变量 b
这是一个指针。在构造函数中,您分配给它指向的内容,但那时它实际上并没有指向任何东西,您覆盖了随机内存。
要么在使用取消引用运算符分配给它指向的位置之前分配指针,要么根本不使用指针(我的建议)。
关于c++ - 模板类关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15618301/