Class Behavior in C

Say I have this:

struct Person {
    char *name;
    char *occupation;
    int years_of_service;
    float salary;
};

and this:

float calculate_salary(struct Person *who){
    float basesalary;

    char *doctor = "Doctor";
    char *janitor = "Janitor";

    int job1 = strcmp(who->occupation, doctor);
    int job2 = strcmp(who->occupation, janitor);

    if(job1 == 0){
        basesalary = 10000.0;
    }
    else if(job2 == 0){
        basesalary = 800.0;
    }

    return basesalary + basesalary*(who->years_of_service*0.1);
}

What is the right way to calculate a person’s salary?

in Python, I would do this in init:

self.salary = self.calculate_salary()

But since C is not OO, I assume that I must first create a person without a paycheck and set a paycheck after. Like this:

struct Person *joe = Person_create("Joe Alex", "Doctor",1);
joe->salary = calculate_salary(joe);

But I would like someone to better understand C to tell me if this is correct.

As a side note, is the line of compassion right? I find this very strange, should I use a switch instead?

+4
source share
2 answers

What is the right way to calculate a person’s salary?

, , struct as . - C.

, python, calculate_salary Person.

struct Person {
    char *name;
    char *occupation;
    int years_of_service;
    float salary;
    float (*fptr)(struct Person *); // fptr is a function pointer
};    

:

int main(void)
{
    struct Person *joe = malloc(sizeof(struct Person));
    joe->name = "Joe Alex";
    joe->occupation = "Doctor";
    joe->years_of_service = 1;

    joe->fptr = calculate_salary; //Function pointer Assignment
    (*joe).salary = (*joe).fptr(joe);
    printf("%f", joe->salary);
}  

, , , .

+9

C

- - . . , , -, , - , .

C , , calculate_salary(). , , C , . person_get_salary().

salary, ( ) person_get_salary().

struct person {
    char *name;
    char *occupation;
    int years_of_service;
};

float person_get_salary(struct person *person)
{
    ...
}

.

float salary = person_get_salary(person);

C .

float salary = person.get_salary();

- . , getter setter .

float salary = person.salary;

, C .

,

. , .

struct person person;

person_init(&person, ...);

float salary = person_get_salary(&person);

...

person_cleanup(&person);

,

.

struct person *person = person_new();

float salary = person_get_salary(person);

...

person_free(person);

person_init() person_new() person_cleanup() person_free() . , , . name occupation .

, , .

, C-, . , . ( ), .

, , , .

, / . , , ( ) .

+6

Source: https://habr.com/ru/post/1569070/


All Articles