С Новым годом! Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.52/21: Рейтинг темы: голосов - 21, средняя оценка - 4.52
0 / 0 / 0
Регистрация: 09.09.2009
Сообщений: 10

Из Form1.h не удается обратиться к функции в main.cpp

09.09.2009, 01:51. Показов 4477. Ответов 7
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Есть project Windows Forms. В обработчике событий на кнопочку нужно использовать стандартные функции, которые есть в Math.h ( abs, log, cos и т.д.) B пользовательские, которые есть в main.cpp. Когда пытаюсь к ним обратиться, вылатает ошибка: error C3861: 'cos': identifier not found (ну и др. такого же плана) Прошу помочь, сам в С++ только начал разбираться, гуглил, но не нашел.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
09.09.2009, 01:51
Ответы с готовыми решениями:

Вызов метода класса Form1 в функции main()
Создаю приложение на Windows Forms. Есть класс Form1: namespace Server { public ref class Form1 : public...

Обратиться к PictureBox на Form1
Всем доброго вечерочка. Нужна помощь... Допустим есть Form1 и Form2. На Form1 расположен PictureBox, а на Form2 расположена кнопка, при...

Main.cpp: In function ‘int main()’: main.cpp:10:1: error: ‘then’ was not declared in this scope
Написал программу и выдает ошибку. #include <iostream> #include <math.h> using namespace std; int main() {double a, b, x; ...

7
Почетный модератор
7393 / 2639 / 281
Регистрация: 29.07.2006
Сообщений: 13,696
09.09.2009, 01:59
Есть project Windows Forms
Это, разве, не .NET?
0
2343 / 499 / 22
Регистрация: 01.04.2009
Сообщений: 2,200
09.09.2009, 08:04
Carbon,
текст приложения, Pls.
по фотографии лечат не здесь.
0
0 / 0 / 0
Регистрация: 09.09.2009
Сообщений: 10
09.09.2009, 12:08  [ТС]
2Vourhey хз...
Maryin_Andrew_1_0.cpp:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Maryin_Andrew_1_0.cpp : main project file.
 
#include "stdafx.h"
#include "Form1.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
using namespace Maryin_Andrew_1_0;
 
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false); 
 
    // Create the main window and run it
    Application::Run(gcnew Form1());
    return 0;
}
Form1.h:
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#pragma once
 
 
namespace Maryin_Andrew_1_0 {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
 
    /// <summary>
    /// Summary for Form1
    ///
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }
 
    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Label^  label1;
    protected: 
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::Label^  label3;
    private: System::Windows::Forms::TextBox^  X;
    private: System::Windows::Forms::TextBox^  Y;
 
 
    private: System::Windows::Forms::TextBox^  N;
 
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::GroupBox^  groupBox1;
    private: System::Windows::Forms::TextBox^  results;
 
    private: System::Windows::Forms::Label^  label5;
    private: System::Windows::Forms::Label^  label4;
    private: System::Windows::Forms::TextBox^  point_place;
    private: System::Windows::Forms::TextBox^  log_error;
    private: System::Windows::Forms::Label^  label6;
    private: System::Windows::Forms::PictureBox^  graphick;
 
 
 
 
    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->label3 = (gcnew System::Windows::Forms::Label());
            this->X = (gcnew System::Windows::Forms::TextBox());
            this->Y = (gcnew System::Windows::Forms::TextBox());
            this->N = (gcnew System::Windows::Forms::TextBox());
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
            this->label6 = (gcnew System::Windows::Forms::Label());
            this->results = (gcnew System::Windows::Forms::TextBox());
            this->log_error = (gcnew System::Windows::Forms::TextBox());
            this->label5 = (gcnew System::Windows::Forms::Label());
            this->label4 = (gcnew System::Windows::Forms::Label());
            this->point_place = (gcnew System::Windows::Forms::TextBox());
            this->graphick = (gcnew System::Windows::Forms::PictureBox());
            this->groupBox1->SuspendLayout();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->graphick))->BeginInit();
            this->SuspendLayout();
            // 
            // label1
            // 
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(47, 58);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(77, 13);
            this->label1->TabIndex = 0;
            this->label1->Text = L"Координата Х";
            // 
            // label2
            // 
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(47, 84);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(77, 13);
            this->label2->TabIndex = 1;
            this->label2->Text = L"Координата Y";
            // 
            // label3
            // 
            this->label3->AutoSize = true;
            this->label3->Location = System::Drawing::Point(109, 110);
            this->label3->Name = L"label3";
            this->label3->Size = System::Drawing::Size(15, 13);
            this->label3->TabIndex = 2;
            this->label3->Text = L"N";
            // 
            // X
            // 
            this->X->Location = System::Drawing::Point(130, 55);
            this->X->Name = L"X";
            this->X->Size = System::Drawing::Size(100, 20);
            this->X->TabIndex = 3;
            // 
            // Y
            // 
            this->Y->Location = System::Drawing::Point(130, 81);
            this->Y->Name = L"Y";
            this->Y->Size = System::Drawing::Size(100, 20);
            this->Y->TabIndex = 4;
            this->Y->TextChanged += gcnew System::EventHandler(this, &Form1::textBox2_TextChanged);
            // 
            // N
            // 
            this->N->Location = System::Drawing::Point(130, 107);
            this->N->Name = L"N";
            this->N->Size = System::Drawing::Size(100, 20);
            this->N->TabIndex = 5;
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(50, 133);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(180, 23);
            this->button1->TabIndex = 6;
            this->button1->Text = L"Посчитать результаты";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            // 
            // groupBox1
            // 
            this->groupBox1->Controls->Add(this->label6);
            this->groupBox1->Controls->Add(this->results);
            this->groupBox1->Controls->Add(this->log_error);
            this->groupBox1->Controls->Add(this->label5);
            this->groupBox1->Controls->Add(this->label4);
            this->groupBox1->Controls->Add(this->point_place);
            this->groupBox1->Location = System::Drawing::Point(50, 188);
            this->groupBox1->Name = L"groupBox1";
            this->groupBox1->Size = System::Drawing::Size(396, 298);
            this->groupBox1->TabIndex = 7;
            this->groupBox1->TabStop = false;
            this->groupBox1->Text = L"Результаты";
            // 
            // label6
            // 
            this->label6->AutoSize = true;
            this->label6->Location = System::Drawing::Point(7, 182);
            this->label6->Name = L"label6";
            this->label6->Size = System::Drawing::Size(50, 13);
            this->label6->TabIndex = 9;
            this->label6->Text = L"Ошибки:";
            // 
            // results
            // 
            this->results->Location = System::Drawing::Point(10, 102);
            this->results->Name = L"results";
            this->results->Size = System::Drawing::Size(380, 20);
            this->results->TabIndex = 3;
            // 
            // log_error
            // 
            this->log_error->Location = System::Drawing::Point(6, 198);
            this->log_error->Multiline = true;
            this->log_error->Name = L"log_error";
            this->log_error->Size = System::Drawing::Size(384, 94);
            this->log_error->TabIndex = 8;
            // 
            // label5
            // 
            this->label5->AutoSize = true;
            this->label5->Location = System::Drawing::Point(7, 86);
            this->label5->Name = L"label5";
            this->label5->Size = System::Drawing::Size(123, 13);
            this->label5->TabIndex = 2;
            this->label5->Text = L"Результат вычислений";
            // 
            // label4
            // 
            this->label4->AutoSize = true;
            this->label4->Location = System::Drawing::Point(7, 25);
            this->label4->Name = L"label4";
            this->label4->Size = System::Drawing::Size(113, 13);
            this->label4->TabIndex = 1;
            this->label4->Text = L"Расположение точки";
            // 
            // point_place
            // 
            this->point_place->Location = System::Drawing::Point(10, 41);
            this->point_place->Name = L"point_place";
            this->point_place->Size = System::Drawing::Size(380, 20);
            this->point_place->TabIndex = 0;
            // 
            // graphick
            // 
            this->graphick->InitialImage = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"graphick.InitialImage")));
            this->graphick->Location = System::Drawing::Point(452, 12);
            this->graphick->Name = L"graphick";
            this->graphick->Size = System::Drawing::Size(539, 521);
            this->graphick->TabIndex = 8;
            this->graphick->TabStop = false;
            this->graphick->WaitOnLoad = true;
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(1003, 545);
            this->Controls->Add(this->graphick);
            this->Controls->Add(this->groupBox1);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->N);
            this->Controls->Add(this->Y);
            this->Controls->Add(this->X);
            this->Controls->Add(this->label3);
            this->Controls->Add(this->label2);
            this->Controls->Add(this->label1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            this->groupBox1->ResumeLayout(false);
            this->groupBox1->PerformLayout();
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->graphick))->EndInit();
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             }
private: System::Void textBox2_TextChanged(System::Object^  sender, System::EventArgs^  e) {
         }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
 
 
            //Выполняем все действия по нажатию на кнопочку.
            int n;
            float R2=3.2,R1=27.4,x,y,Y_=-20.5;
            bool type_of_data = true;
 
            /*if(strcmp(N->Text,'')) {log_error->Text+="Вы не ввели n\n"; type_of_data=false; } 
            if(strcmp(X->Text,'')) {log_error->Text+="Вы не ввели x\n"; type_of_data=false; } 
            if(strcmp(Y->Text,'')) {log_error->Text+="Вы не ввели y\n"; type_of_data=false; } */
            if(type_of_data==true) {
            n = Convert::ToInt16(N->Text);
            x=Convert::ToDouble(X->Text);
            y=Convert::ToDouble(Y->Text);
            if(x*x+y*y<R2*R2) {
            point_place->Text="Точка находится вне фигуры (внутри круга)!";
 
            results->Text=Convert::ToString(R2-R1);
            //точка в центральном круге.
 
            }else {
                 //точка вне круга
                 if(y>=0) {
                    point_place->Text="Точка выше оси Х и находится вне фигуры";
                    results->Text=Convert::ToString(R2-R1);
                    //точка над фигурой
                    if(x*x+y*y<=R1*R1) {
                    point_place->Text="Точка выше оси Х и находится в фигуре";
                    //точка в фигуре сверху
                    if(x>=0) {
//A1
                        results->Text=Convert::ToString(function_A1(x,y,n));
                        } else {
//A2                    
                        results->Text=Convert::ToString(function_A2(x,y,n,R1));
                        }
                    }
                 } else {
                     
                        point_place->Text="Точка ниже оси Х и находится вне фигуры";
                        results->Text=Convert::ToString(R2-R1);
                        if(y>=Y_ && x<=abs(R1)) {
                        point_place->Text="Tочка ниже оси Х и находится в фигуре";
                        if(x>=0) {
//A1
                        results->Text=Convert::ToString(function_A1(x,y,n));
                        } else {
//A2                    
                        results->Text=Convert::ToString(function_A2(x,y,n,R1));
                        }
                     } else {
                            point_place->Text="Точка ниже оси Х и находится слева или справа от фигуры";
                        results->Text=Convert::ToString(R2-R1);
                        
                        }
                 }
             }
 
         }
 
 
         }
                     int abs(int n) {
if(n<0) return -n; else return n;
//Написал свой abs, чтобы опробывать работу, но свой log и cos писать влом.
             }
                            double function_A1(double x,double y,double n) {
                                return 1;
        //return (-x*(1-x*y-(x*x/y)))/(1+x*x/y - log(x)+cos(x/y) + x) + fibon(n);
        }
        double function_A2(double x,double y,double n,double R) {
//Не работают функции abs, cos и др. Если вставить в cpp файл пользовательские функции, то они тоже перестанут работать.
        //return ((R+7.39)*x*0.001)/pow(x,pow(5,1.4/y-1))+(-x*(1-x*y+x*x/y)/(1+x*x/y-log(x)+cos(x/y)+x)) + factorial_(n);
            return 2;
        }
};
}
Не работают функции abs, cos и др (хотя в cpp файле стоит include<math.h>. Если вставить в cpp файл пользовательские функции, то они тоже перестанут работать.
0
 Аватар для HIMen
4340 / 1509 / 101
Регистрация: 12.04.2009
Сообщений: 2,342
09.09.2009, 17:28
Используй System::Math:: там есть все стандартные математические функции.

Если нужны свои функции, то создавай myheder.h , пиши в нем их объявления,
и myheder.cpp - в нем сами функции,
затем в начале Form1.h добавляй #include "myheder.h"
1
0 / 0 / 0
Регистрация: 09.09.2009
Сообщений: 10
09.09.2009, 20:13  [ТС]
Спасибо огромное, а ты не мог бы пример написать, что написать в myheader.h и myheader.cpp.
Ещё вопрос, название у этих двух файлов должно совпадать?
0
 Аватар для HIMen
4340 / 1509 / 101
Регистрация: 12.04.2009
Сообщений: 2,342
09.09.2009, 22:16
Цитата Сообщение от Carbon Посмотреть сообщение
Ещё вопрос, название у этих двух файлов должно совпадать?
Нет, не обязательно, но когда твоя программа разрастется до нескольких файлов будешь путаться, поэтому лучше называть одинаково.
Вот простой пример на vs2008
Вложения
Тип файла: rar app.rar (75.7 Кб, 202 просмотров)
0
0 / 0 / 0
Регистрация: 09.09.2009
Сообщений: 10
09.09.2009, 23:12  [ТС]
спасибо большое! Этот пример очень многое показал)!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
09.09.2009, 23:12
Помогаю со студенческими работами здесь

Main.cpp In file included from main.cpp
//class.cpp #include &quot;class.h&quot; Ticket::Ticket() { prise = 0; marshrut = &quot;none&quot;; time = &quot;none&quot;; ...

Как передать переменные и массивы из main.cpp в mainwindow.cpp?
Как передать переменные и массивы из main.cpp в mainwindow.cpp? main.cpp #include &quot;mainwindow.h&quot; #include &lt;QApplication&gt; ...

Подключение файлов main.cpp some.cpp some.h
Всем привет, программа разделенна на три файла poly.cpp main.cpp poly.h Кто мог бы объяснить как происходит подключение этих файлов, и как...

Вот: source_file.cpp: In function 'int main()': source_file.cpp:10:12: error: 'strlen' was not declared in this scope
#include&lt;iostream&gt; using namespace std; int main() { char a,b; int i,j; cout&lt;&lt;&quot;Напишите слово:&quot;; cin&gt;&gt;a; i=0; ...

Метод Main не видит Form1
Нашел одну программку, она работает. Скопировал код к себе,чтобы местами код,а он выдает ошибку using System; using...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Новые блоги и статьи
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и напряжениями. Надо найти токи в ветвях. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и решает её. Последовательность действий:. . .
Новый CodeBlocs. Версия 25.03
palva 04.01.2026
Оказывается, недавно вышла новая версия CodeBlocks за номером 25. 03. Когда-то давно я возился с только что вышедшей тогда версией 20. 03. С тех пор я давно снёс всё с компьютера и забыл. Теперь. . .
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru