Home > front end >  How to understand this expression in C struct?
How to understand this expression in C struct?

Time:09-23

struct Task{
    int value,time,deadline;
    bool operator < (const Task& t1)const{
        return d<t1.deadline;
    }
}task[1000];

I've read this block of code of struct initialization. the first line, initialize variables, is easy to grasp. What about the second line? the bool operator thing. Seems like some kind of sorting rules. I have never seen any code like this in cpp before, could someone help me to understand it?

CodePudding user response:

What you observe is called operator overloading. In this case the operator< is overloaded for class Task.

This is done in order to be able to write something like this.

Task t1{1,2,3};
Task t2{2,3,4};
if(t1 < t2) //note, the operator<  is called
{
    //do your thing
}

CodePudding user response:

To add to the answer, I would like to point out that the variables are not initialized (in traditional sense). It is so called default initialization or, rather, a lack of initialization as the variables will be of whatever value that happened to be in the memory at that time.

To zero-initialize the array, you'll need to use the following syntax (that resembles calling a default constructor of an array)

struct Task{
    int value, time, deadline;

    bool operator < (const Task& t1) const {
        return deadline < t1.deadline;
    }
} task[1000]{};

...Well, it's simple in your case, since you don't have any user-declared constructors, but in other cases it may become tricky. Read this if you're interested value-initialization.

(And {} is a new syntax for constructing objects introduced in C 11. The prior syntax () has several issues: it does not check that arguments are narrowed, and it suffers from the most vexing parse problem, when Foo aVariable(std::string("bar")); is parsed as function declaration (see).)

  • Related