对象初始化和循环内部' for'?

时间:2016-03-05 09:52:46

标签: c++ class loops constructor operator-overloading

我今天参加了面试,面试官问我以下问题要在课堂上实施和填写代码。

dim lastRow as long
with ws
    lastRow = .cells(.rows.count, "E").end(xlup).row
    'option 1
    .range("B5:D" & lastRow).select

    'option 2
    with .range("E5:E" & lastRow)
        .offset(0, -3).resize(.rows.count, 3).select
    end with

    'option 3
    .range("E5", .cells(lastRow, "G")).offset(0, -3).select
end with

我不清楚,我无法回答。有人能让我知道这个问题吗?

2 个答案:

答案 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;
}

答案 1 :(得分:1)

看一下这句话

for(I i=0; i<10; i++){

它遵循以下结构

I i=0;
i<10;
i++

有效。

因此,类需要一个(非显式)构造函数,它可以接受int类型的对象作为参数。该类应具有可访问的副本或移动构造函数。

对于类的对象或者当一个操作数可以是int类型时,应该声明operator <

该类需要后缀增量运算符operator ++

这是一个示范性的计划。我添加了运算符&lt;&lt;为清楚起见。

#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
相关问题