縱觀本聲明
for(I i=0; i<10; i++){
它遵循以下結構
I i=0;
i<10;
i++
應有效。
所以這個類需要一個(非顯式的)構造函數,它可以接受一個int類型的對象作爲參數。並且該類應該有一個可訪問的副本或移動構造函數。
對於類的對象或當一個操作數可以是int類型時,應聲明operator <
。
而這個類需要後綴增量運算符operator ++
。
這是一個演示程序。爲了清楚起見,我添加了運營商< <。
#include <iostream>
class I
{
public:
I(int i) : i(i) {}
I(const I &) = default;
bool operator <(const I &rhs) const
{
return i < rhs.i;
}
I operator ++(int)
{
I tmp(*this);
++i;
return tmp;
}
friend std::ostream & operator <<(std::ostream &, const I &);
private:
int i;
};
std::ostream & operator <<(std::ostream &os, const I &obj)
{
return os << obj.i;
}
int main()
{
for (I i = 0; i < 10; i++)
{
std::cout << i << ' ';
}
std::cout << std::endl;
}
程序輸出是
0 1 2 3 4 5 6 7 8 9
如果你想,這個循環將是有效的
for (I i = 10; i; )
{
std::cout << --i << ' ';
}
那麼類定義可以像
#include <iostream>
class I
{
public:
I(int i) : i(i) {}
I(const I &) = default;
explicit operator bool() const
{
return i != 0;
}
I & operator --()
{
--i;
return *this;
}
friend std::ostream & operator <<(std::ostream &, const I &);
private:
int i;
};
std::ostream & operator <<(std::ostream &os, const I &obj)
{
return os << obj.i;
}
int main()
{
for (I i = 10; i; )
{
std::cout << --i << ' ';
}
std::cout << std::endl;
}
程序輸出是
9 8 7 6 5 4 3 2 1 0
您必須實現循環中使用的這三個運算符。 – MikeCAT
您的I必須與可能的數據類型10 –
@MikeCAT相似您的意思是=,<和++運算符?哦運營商超載。 – highlander141