LINUX.ORG.RU

Ошибка типа структуры в C++

 , ,


0

0
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
struct Third
{
 int first;
 double second;
 bool third;
};
struct Second
{
 Third fifth;
 char other;
};
Second fourth = {{1,2.2,true},'F'};
void p(Second zero)
{
 int &a = zero.fifth.first;
 double &b =zero.fifth.second;
 bool &c = zero.fifth.third;
 std::cout<<"Third: "<<a<<"\n";
 std::cout<<"Second: "<<b<<"\n";
 std::cout<<"First: "<<c<<"\n";
 std::cout<<"Four: "<<zero.other;
}
int main()
{
 p(fourth);
 return 0;
}

//Код сверху пропускает без проблем с ожидаемым результатом,

//но код снизу вызывает краш в месте инициализации переменной (Second fourth). Коды практически идентичны, объясните, что не так? Error: unknown type name 'fourth'

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
struct Third
{
 int first;
 double second;
 bool third;
};
struct Second
{
 Third fifth;
 char other;
};
Second fourth;
fourth.fifth.first = 1;
fourth.fifth.second = 2.2;
fourth.fifth.third = true;
fourth.other ='f';
void p(Second zero)
{
 int &a = zero.fifth.first;
 double &b =zero.fifth.second;
 bool &c = zero.fifth.third;
 std::cout<<"Third: "<<a<<"\n";
 std::cout<<"Second: "<<b<<"\n";
 std::cout<<"First: "<<c<<"\n";
 std::cout<<"Four: "<<zero.other;
}
int main()
{
 p(fourth);
 return 0;
}

fourth.fifth.first = 1;
fourth.fifth.second = 2.2;
fourth.fifth.third = true;
fourth.other ='f';

Вот это в блок main унеси, перед вызовом p. Ты не можешь выполнять какой либо код вне функций. Только объявлять переменные с их инициализацией. По-этому первый код работает, а второй нет.

Error: unknown type name 'fourth' - тут компилятор ожидает, что ты объявляешь переменную, но это не так.

pozitiffcat ★★★
()

eще так можешь сделать тогда ничего никуда переносить не надо.

Second fourth {

fourth.fifth.first = 1,
fourth.fifth.second = 2.2,
fourth.fifth.third = true,
fourth.other ='f',

};

anonymous
()

Так обычно инициализируют статические члены данных. Форма в духе тип член = значение

struct foo { static int int_field;};
int foo::int_field = 4;

Поэтому компилятор и пишет, что там должен был быть тип, а там не понятно что.

zerhud
()
Second fourth{1,2.2,true,'f'};
thunar ★★★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.