Zetton
Zetton

Reputation: 19

Protocol-Buffers C++ can't set variables

I'm new to C++ (and programming overall). Trying to understand protobuf and have some issues. Here is the proto file:

syntax="proto3";

message FullName{
    string Surname = 1;
    string Name = 2;
    optional string Patronymic = 3;
}

message Student{
    FullName sName = 1;
    repeated int32 Grade = 2;
    int32 AverageMark = 3;
}

message StudentsGroup{
    repeated Student sInfo = 1;
}

and here is the code:

#include <iostream>
#include "Students.pb.h"

int average(const google::protobuf::RepeatedField<int32_t>& grades)
{
    int32_t s = 0;
    for (const int& i : grades)
    {
        s = s + i;
    }
    return s/grades.size();
}


int main()
{
    FullName name1;
    name1.set_surname("Sergeev");
    name1.set_name("Sergey");
    name1.set_patronymic("Sergeevich");
    std::cout << name1.name() << std::endl;

    Student student1;
    student1.set_name(name1);  // <--
    student1.add_grade(4);
    student1.add_grade(3);
    student1.set_averagemark(average(student1.grade()));

    StudentsGroup group1;
    group1.add_sinfo(student1);  // <--

}

The issue is I don't know how to set student1 sName and add sInfo in group1. The syntax I use is incorrect. Please help)

Upvotes: 0

Views: 626

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38612

  1. Student has no Name field, thus Student::set_name() cannot be available.
  2. Student has FullName sName, FullName is not a base type, thus the setter is Student::set_allocated_sname(::FullName* sname).
  3. Student sInfo = 1 is repeated values of not a base type in StudentsGroup, thus it should be accessed through the mutable collection ::google::protobuf::RepeatedPtrField<::Student>* StudentsGroup::mutable_sinfo()

The fix:

auto name1 = std::make_unique<FullName>();
name1->set_surname("Sergeev");
name1->set_name("Sergey");
name1->set_patronymic("Sergeevich");
std::cout << name1->name() << std::endl;

auto student1 = std::make_unique<Student>();
student1->set_allocated_sname(name1.release());
student1->add_grade(4);
student1->add_grade(3);
student1->set_averagemark(average(student1->grade()));

StudentsGroup group1;
group1.mutable_sinfo()->AddAllocated(student1.release());

Upvotes: 1

Related Questions