'for'中的对象初始化和循环?

问题描述:

我今天参加了一个采访,面试官问我下面的问题来实现并在课堂中填入代码。'for'中的对象初始化和循环?

class I 
{ 
// code to be filled in 
..... 
..... 
..... 
}; 
int main() 
{ 
for(I i=0; i<10; i++){ // to make this for loop work, what needs to be written in the class above? 
cout << " " << endl; 
} 
...... 
...... 
return 0; 
} 

对我不明确,我无法回答。有人可以让我知道这个问题吗?

+1

您必须实现循环中使用的这三个运算符。 – MikeCAT

+1

您的I必须与可能的数据类型10 –

+0

@MikeCAT相似您的意思是=, highlander141

纵观本声明

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 

您需要实现所需的运营商(<++)和匹配的构造函数(I(int)):

#include <iostream> 

using namespace std; 

class I 
{ 
private: 
    int index; 

public: 
    I(const int& i) : index(i) {} 

    bool operator<(const int& i) { 
     return index < i; 
    } 

    I operator++(int) { 
     I result(index); 
     ++index; 
     return result; 
    } 
}; 

int main() 
{ 
    for(I i=0; i<10; i++){ // to make this for loop work, what needs to be written in the class above? 
     cout << "A" << endl; 
    } 
    return 0; 
}