2016-03-05 56 views
-1

我今天參加了一個採訪,面試官問我下面的問題來實現並在課堂中填入代碼。'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

回答

1

縱觀本聲明

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 
2

您需要實現所需的運營商(<++)和匹配的構造函數(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; 
}