我编写了一个Dice
模仿真实骰子行为的小类和可以继承的模板Singleton
类Dice
。我已经operator<<
为类写了,Dice
但不知何故编译器在找到它时遇到了问题。我为 , 重载了<<
运算符Dice
,它是从某些方法返回的,拥有它很方便。Sinlgeton<Dice>
std::vector<int>
Dice
我在 ubuntu 上使用Qt creator 2.5
with 。gcc 4.7
/home/USER/programming/cpp_yahtzee/main.cpp:12: 错误: 'std::operator<< >(((* & std::cout), ((const char*) "你好")) << (& Singleton::Instance())->Dice::getLastThrow()'</p>
这是产生此错误的代码:
std::cout << "hello" << Dice::Instance().getLastThrow();
编辑
然而,这输出了预期的结果,完全没有错误:
std::cout << Dice::Instance()
也许这是我的编译器的问题gcc/g++ 4.7
(尝试过gcc/g++ 4.6.3
并且效果相同)?
我的单人班
template <typename T>
class Singleton
{
public:
static T& Instance();
Singleton() {}
private:
//declare them to prevent copies
Singleton(Singleton const&);
void operator=(Singleton const&);
};
template<typename T>
T& Singleton<T>::Instance()
{
static T _instance;
return _instance;
}
骰子类:
class Dice : public Singleton<Dice>
{
private:
std::vector<int> _lastThrow;
public:
Dice();
std::vector<int> generateThrow();
friend std::ostream& operator<<(std::ostream& os, const Dice& dice);
friend std::ostream& operator<<(std::ostream& os, const Singleton<Dice>& dice);
friend std::ostream& operator<<(std::ostream& os, const std::vector<int>& vect);
//accessor method - returning last throw
const std::vector<int>& getLastThrow();
//rethrowing {1,4} - dice #1 and #4
std::vector<int> Rethrow(const std::vector<int>& objects);
};
std::ostream& operator<<(std::ostream& os, const Dice& dice)
{
for (std::vector<int>::const_iterator it = dice._lastThrow.begin(); it != dice._lastThrow.end(); ++it) {
os << *it;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const Singleton<Dice>& dice)
{
for (std::vector<int>::const_iterator it = dice.Instance().getLastThrow().begin(); it != dice.Instance().getLastThrow().end(); ++it) {
os << *it;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const std::vector<int>& vect)
{
for (std::vector<int>::const_iterator it = vect.begin(); it != vect.end(); ++it) {
os << *it;
}
return os;
}
std::vector<int> Dice::generateThrow()
{
static std::vector<int> v(5);
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
(*it) = rand()%(DICE_MAX)+1;
}
_lastThrow = v;
return v;
}
现在我不能做这样的事情:
std::cout << Dice::Instance().generateThrow();
编辑
Ilya Lavrenov 的方法有效,尽管这不是我想要的,因为这需要创建一个局部变量。我在课堂上的某个地方有问题Singleton
。