C2601 c как исправить

Error C2601: main: недопустимые локальные определения функций C++ Решение и ответ на вопрос 1238226

Vladislavv

1 / 1 / 2

Регистрация: 30.07.2014

Сообщений: 98

1

04.08.2014, 13:13. Показов 4800. Ответов 1

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <ctime>
using namespace std;
 
int dieroll (){
int chance=0;
srand (time(NULL));
chance=rand()%1000;
chance%=7;
return chance;
}
 
int summ (int s){
s+=s;
return s;
}
 
void winner (int pl, int comp){
if (pl>comp)
    cout <<"pl win the gamen";
else
    (comp>pl)? cout<<"comp win the gamen":cout <<"drawn";
}
 
bool ftt (){
bool fm=0;
srand (time(NULL));
fm=(rand()%1000)%2;
return fm;
}
 
void inscfft (){
    bool insc=ftt();
    if (insc==0)
        cout <<"comp throw firstn";
    else 
        cout <<"pl throw firstn";
}
 
void move (int mv, int trn, int pl, int comp){
    if (mv==0){
    cout <<"comp"<<trn<<"trow "<<comp<<endl;
    cout <<"pl"<<trn<<"trow "<<pl<<endl;
    }
    else{
    cout <<"pl"<<trn<<"trow "<<pl<<endl;
    cout <<"comp"<<trn<<"trow "<<comp<<endl;
    }
        
void main(){
    inscfft ();
    const int n=5;
int pl[n], comp[n], plsc=0, compsc=0;
for (int i=0; i<n;i++){
    pl[n]=dieroll ();
    plsc+=summ (pl[n]);
}
for (int i=0; i<n;i++){
    comp[n]=dieroll ();
    compsc+=summ (comp[n]);
}
bool chance=ftt;
for (int i=0; i<n; i++)
move (chance, i, pl[i], comp[i]);
winner (plsc, compsc);
}

пишет
6 IntelliSense: expected a ‘;’
4 error C2601: main: недопустимые локальные определения функций
5 error C1075: конец файла обнаружен ранее, чем левая фигурная скобка «{» в «c:usersвладdocumentsvisual studio 2010projectsles 8les 8dice.cpp(40)»
не пойм, где эти ошибки

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



16495 / 8988 / 2205

Регистрация: 30.01.2014

Сообщений: 15,611

04.08.2014, 13:18

2

Цитата
Сообщение от Vladislavv
Посмотреть сообщение

void move (int mv, int trn, int pl, int comp)

У этой функции закрывающую скобку забыл.

PS. На будущее пользуйся пожалуйста тегами форматирования кода при создании постов и тем.



1



Я пишу небольшую программу на C ++. Когда я пытаюсь скомпилировать его с помощью MS VS 2013 Compiler, я получаю сообщение об ошибке: «C2601:« main »: определения локальных функций недопустимы». Что это значит? Мой код:

#include <iostream>
int n;
int pomocniczaLiczba;
using namespace std;
int ciong(int n){
switch (n)
{
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
pomocniczaLiczba = ciong(n - 2) + ciong(n - 1) * ciong(n - 1);
return pomocniczaLiczba;
break;
}
int main()
{
cin >> n;
cout >> ciong(n);
return 0;
}
}

-1

Решение

Ваш брекетинг сломан. В результате вы пытаетесь определить свой main функция внутри ciong, А C ++ не поддерживает определения вложенных функций. Отсюда ошибка компилятора.

Код должен быть:

#include "stdafx.h"#include <iostream>
using namespace std;int ciong(int n)
{
switch (n)
{
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
int pomocniczaLiczba = ciong(n - 2) + ciong(n - 1) * ciong(n - 1);
return pomocniczaLiczba;
break;
}
} // <----- Oops, this was missing in your code

int main()
{
int n;
cin >> n;
cout << ciong(n) << endl;
return 0;
}

И есть другие ошибки. Например, вы имели в виду cout << ciong(n),

12

Другие решения

Используя Visual Studio 2013 C ++, я получил ошибки компиляции, которые я не смог объяснить.

Ошибки компиляции были:

* main.cpp (325): ошибка C2601: «FLAG»: определения локальных функций недопустимы

main.cpp (323): эта строка содержит ‘{‘, который еще не был найден

main.cpp (326): фатальная ошибка C1075: обнаружен конец файла до сопоставления левой скобки ‘{‘ at ‘main.cpp (323)’ *

Но с моим кодом не было ничего плохого. Я посчитал все скобки и число совпало. Там не было никакой функции внутри другой функции.

Я решил это, удалив все комментарии «//» из исходного кода. Кажется, что причиной этого является плохое форматирование строки, из-за которого компилятор пропускает разрыв строки, поэтому строка после комментария также рассматривается как комментарий.

Например:

// This is a comment

This_is_a_line;

рассматривается как:

// This is a comment This_is_a_line;

Есть много сообщений в сети о подобных проблемах, и некоторые даже предположили, что они могут быть вызваны ошибкой памяти (RAM) на машине, поэтому, прежде чем заменять свою RAM, просто удалите комментарии и посмотрите …

  • Майкл Хефрати מיכאל האפרתי

0

I’m new to C++ and learning about Inheritance and Polymorphism. We require to write an employee project that have 4 types of employee (BasePlusCommission, CommisisonEmployee, Salaried and TipWorker). My project has one main() class that I used switch method for each type of employee. I got stuck on TipWorker where we have to do Polymorphism. Here what I got so far.

int main()
{
void virtualViaPointer(const Employee * const);
    {
                cout << "Enter First Name: " << endl;
                cin >> firstName;
                cout << "Enter Last Name: " << endl;
                cin >> lastName;
                cout << "Enter SSN: " << endl;
                cin >> SSN;
                if (SSN.length() == 9)
                {
                    SSN = true;
                }
                else
                {
                    cout << "Please enter SSN again with 9 digits only:" << endl;
                    cin >> SSN;
                }
                cout << "Enter wages: " << endl;
                cin >> wage;
                cout << "Enter hours: " << endl;
                cin >> hours;
                cout << "Enter tips: " << endl;
                cin >> tips;

                TipWorker employee4(firstName, lastName, SSN, wage, hours, tips);
                employee4.print();
                cout << fixed << setprecision(2);

                vector < Employee * > employees(1);
                employees[0] = &employee4;

                cout << "Employee processed polymorphically via dynamic binding: nn";
                cout << "Virtual function calls made off base-class pointers:nn";
                for (const Employee *employeePtr : employees)
                    virtualViaPointer(employeePtr);
                void virtualViaPointer(const Employee * const baseClassPtr)
                {
                    baseClassPtr->print();
                    cout << "nEarned $" << baseClassPtr->earnings() << "nn";
                }
                    break;
      }
}

When I run the project, I came up with this error:

error C2601: «virtualViaPointer»: local function definitions are
illegal

void virtualViaPointer(const Employee * const baseClassPtr)
                    {
                        baseClassPtr->print();
                        cout << "nEarned $" << baseClassPtr->earnings() << "nn";
                    }

Can anyone please help me? Thank you so much!

I’m new to C++ and learning about Inheritance and Polymorphism. We require to write an employee project that have 4 types of employee (BasePlusCommission, CommisisonEmployee, Salaried and TipWorker). My project has one main() class that I used switch method for each type of employee. I got stuck on TipWorker where we have to do Polymorphism. Here what I got so far.

int main()
{
void virtualViaPointer(const Employee * const);
    {
                cout << "Enter First Name: " << endl;
                cin >> firstName;
                cout << "Enter Last Name: " << endl;
                cin >> lastName;
                cout << "Enter SSN: " << endl;
                cin >> SSN;
                if (SSN.length() == 9)
                {
                    SSN = true;
                }
                else
                {
                    cout << "Please enter SSN again with 9 digits only:" << endl;
                    cin >> SSN;
                }
                cout << "Enter wages: " << endl;
                cin >> wage;
                cout << "Enter hours: " << endl;
                cin >> hours;
                cout << "Enter tips: " << endl;
                cin >> tips;

                TipWorker employee4(firstName, lastName, SSN, wage, hours, tips);
                employee4.print();
                cout << fixed << setprecision(2);

                vector < Employee * > employees(1);
                employees[0] = &employee4;

                cout << "Employee processed polymorphically via dynamic binding: nn";
                cout << "Virtual function calls made off base-class pointers:nn";
                for (const Employee *employeePtr : employees)
                    virtualViaPointer(employeePtr);
                void virtualViaPointer(const Employee * const baseClassPtr)
                {
                    baseClassPtr->print();
                    cout << "nEarned $" << baseClassPtr->earnings() << "nn";
                }
                    break;
      }
}

When I run the project, I came up with this error:

error C2601: «virtualViaPointer»: local function definitions are
illegal

void virtualViaPointer(const Employee * const baseClassPtr)
                    {
                        baseClassPtr->print();
                        cout << "nEarned $" << baseClassPtr->earnings() << "nn";
                    }

Can anyone please help me? Thank you so much!

Using Visual Studio 2013 C++, I got compilation errors that I couldn’t explain.

The compilation errors were:

*main.cpp(325): error C2601: ‘FLAG’ : local function definitions are illegal

main.cpp(323): this line contains a ‘{‘ which has not yet been matched

main.cpp(326): fatal error C1075: end of file found before the left brace ‘{‘ at ‘main.cpp(323)’ was matched*

But there was nothing wrong with my code. I counted all brackets and the number matched. There weren’t any function inside another function.

I solved it by removing all «//» comments from the source code. It seems that the reason for that is bad line formatting which causes the compiler to miss a line break, so the line after a comment is treated as a comment as well.

For example:

// This is a comment

This_is_a_line;

is treated as:

// This is a comment This_is_a_line;

There are many posts of the net about similar problems and some even suggested that they could be caused by a memory (RAM) fault on the machine, so before you replace your RAM, just remove the comments and see…

  • Michael Haephrati מיכאל האפרתי

Когда я пытаюсь запустить код, который я нашел в Интернете, я получаю следующие ошибки:

Ошибка C2601 «get_wallpaper_window»: определения собственных функций недействительны.

Ошибка C2601 «EnumWindowsProc»: недопустимые определения локальных функций

Ошибка C2065 «EnumWindowsProc»: необъявленный идентификатор

Ошибка (активная) E0065 ожидала ‘;’

У меня мало знаний в области кодирования, поэтому я не очень понимаю ошибки, я был бы признателен, если бы вы могли помочь. Код здесь:

Void button1_Click_2(System::Object^ sender, System::EventArgs^ e) {
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    HWND p = FindWindowEx(hwnd, NULL, L"SHELLDLL_DefView", NULL);
    HWND* ret = (HWND*)lParam;

    if (p)
    {
        // Gets the WorkerW Window after the current one.
        *ret = FindWindowEx(NULL, hwnd, L"WorkerW", NULL);
    }
    return true;
}

HWND get_wallpaper_window()
{
    // Fetch the Progman window
    HWND progman = FindWindow(L"ProgMan", NULL);
    // Send 0x052C to Progman. This message directs Progman to spawn a 
    // WorkerW behind the desktop icons. If it is already there, nothing 
    // happens.
    SendMessageTimeout(progman, 0x052C, 0, 0, SMTO_NORMAL, 1000, nullptr);
    // We enumerate all Windows, until we find one, that has the SHELLDLL_DefView 
    // as a child. 
    // If we found that window, we take its next sibling and assign it to workerw.
    HWND wallpaper_hwnd = nullptr;
    EnumWindows(EnumWindowsProc, (LPARAM)&wallpaper_hwnd);
    // Return the handle you're looking for.
    return wallpaper_hwnd;
}
}

Спасибо

1 ответ

Вы определяете свои функции EnumWindowsProc() и get_wallpaper_window() внутри функции button1_Click_2(). С++ не позволяет этого, о чем и говорят ошибки компилятора. Функции должны быть перемещены наружу, например

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    HWND p = FindWindowEx(hwnd, NULL, L"SHELLDLL_DefView", NULL);
    HWND* ret = (HWND*)lParam;

    if (p)
    {
        // Gets the WorkerW Window after the current one.
        *ret = FindWindowEx(NULL, hwnd, L"WorkerW", NULL);
    }
    return true;
}

HWND get_wallpaper_window()
{
    // Fetch the Progman window
    HWND progman = FindWindow(L"ProgMan", NULL);
    // Send 0x052C to Progman. This message directs Progman to spawn a 
    // WorkerW behind the desktop icons. If it is already there, nothing 
    // happens.
    SendMessageTimeout(progman, 0x052C, 0, 0, SMTO_NORMAL, 1000, nullptr);
    // We enumerate all Windows, until we find one, that has the SHELLDLL_DefView 
    // as a child. 
    // If we found that window, we take its next sibling and assign it to workerw.
    HWND wallpaper_hwnd = nullptr;
    EnumWindows(EnumWindowsProc, (LPARAM)&wallpaper_hwnd);
    // Return the handle you're looking for.
    return wallpaper_hwnd;
}

Void button1_Click_2(System::Object^ sender, System::EventArgs^ e)
{
    get_wallpaper_window();
}


0

Remy Lebeau
21 Мар 2021 в 23:06

Lusika


  • #1

Подскажите пожалуйста. У меня есть пара функций, есть для них прототипы, а компилер говорит, что неправильное определение функций, я сомтрела в мсдн по коду ошибки, но не разобралась.

Может я не туда прототипы сую?
У меня проект создан через MFC AppWizard; соответственно файлы myproj.cpp myproj.h myprojDlg.cpp myprojDlg.h
я прототипы в myprojDlg.h ставлю:

Код:

int dayInMonth(int numb_month, int year);
bool checkvisokos(int god);

вот сам пример исользования функций:

Код:

void CMyprojDlg::OnOK() 
{
UpdateData (TRUE);
int dayInMonth(int numb_month, int year)
{	int dIm;
switch(numb_month)
{ 
case '1':{dIm=31;;break; }
case '2':{ if !(checkvisokos(year)) {dIm=28;}else {dIm=29;} break;}
case '3':{dIm=31; break;}
case '4':{dIm=30; break;}
case '5':{dIm=31; break;}
case '6':{dIm=30; break;}
case '7':{dIm=31; break;}
case '8':{dIm=31; break;}
case '9':{dIm=30; break;}
case '10':{dIm=31;break;}
case '11':{dIm=30;break;}
case '12':{dIm=31;break;}

}
return dIm;
} 
bool checkvisokos(int god)
{
if ( div(god,4).rem ==0) {return true;}else {return false;}
}
... 
int nM = currt.GetMonth(); 
int nY = currt.GetYear();
int dify=nY-dry;
int difm=nM-drm;
int difd=nD-drd;
...
if (difd <0){int res= dayInMonth(nM,nY);difm=difm-1;difd=difd+res;}
.......
}

Lusika


  • #2

Я вынесла функции из другой функции, а теперь линковщик ругается:
ну вот…перенесла функции…закомпилилось, но теперь линковщик ругается:
error LNK2001: unresolved external symbol «public: int __thiscall CMyprojDlg::dayInMonth(int,int,bool)» (?dayInMonth@CMyprojDlg@@QAEHHH_N@Z)

и на вторую функцию тоже :-(

SunSanych


  • #3

Линковщик говорит, что Вы пытаетесь вызвать функцию класса CMyprojDlg с именем dayInMonth и тремя переменными имеющие тип int, int, bool. А такой функции нет.
И он прав. Так как, если Вы ничего не меняли, то Ваши функции не принадлежат классу CMyprojDlg, а являются глобальными, а функция dayInMonth имеет только два параметра с типом int.
Скорее всего Вы просто передали в функцию лишнюю переменную. Проверьте еще раз по-внимательнее.
Или, вариант, что вы эти две функции определили в теле класса CMyprojDlg (из листинга это не понятно), тогда их надо или вынести от туда или их реализацию начинать так
intCMyprojDlg::dayInMonth
и
bool CMyprojDlg::checkvisokos
но тогда их нельзя будет использовать в других классах.
Удачи.

Lusika


  • #4

Спасиб, разобралась, у меня прототипы всё же были не там.

Понравилась статья? Поделить с друзьями:
  • C2600 ошибка приус 10
  • C2577 ошибка приус
  • C2558 konica minolta 185 сброс ошибки
  • C2544 ошибка субару
  • C2498 ошибка мерседес w211