0

Здравствуйте! Помогите, пожалуйста решить несколько проблем.

Проблема 1:

В начале файла указал #include "DataBase.h" и #include "ProfileFind.h", но по ошибкам такое чувство, будто бы таких строк не существует.

#pragma once
#include "DataBase.h"
#include "ProfileFind.h"
#include "CriminalCaseAdd.h"

namespace Coursach {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Text;

/// <summary>
/// Сводка для MainMenu
/// </summary>
public ref class MainMenu : public System::Windows::Forms::Form
{
public:
    MainMenu(void)
    {
        InitializeComponent();

        db = gcnew DataBase();
    }

protected:
    /// <summary>
    /// Освободить все используемые ресурсы.
    /// </summary>
    ~MainMenu()
    {
        if (components)
        {
            delete components;
        }

    }

private: DataBase ^ db;

private: System::Windows::Forms::Label^  mainMenu_label;
private: System::Windows::Forms::Button^  profileAdd;

private: System::Windows::Forms::GroupBox^  groupBox1;
private: System::Windows::Forms::Button^  profileStat;

private: System::Windows::Forms::Button^  profileFind;

private: System::Windows::Forms::GroupBox^  groupBox2;
private: System::Windows::Forms::Button^  ccStat;

private: System::Windows::Forms::Button^  ccFind;
private: System::Windows::Forms::Button^  ccAdd;

private:
    /// <summary>
    /// Обязательная переменная конструктора.
    /// </summary>
    System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
    /// <summary>
    /// Требуемый метод для поддержки конструктора — не изменяйте 
    /// содержимое этого метода с помощью редактора кода.
    /// </summary>
    void InitializeComponent(void)
    {
        this->mainMenu_label = (gcnew System::Windows::Forms::Label());
        this->profileAdd = (gcnew System::Windows::Forms::Button());
        this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
        this->profileStat = (gcnew System::Windows::Forms::Button());
        this->profileFind = (gcnew System::Windows::Forms::Button());
        this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());
        this->ccStat = (gcnew System::Windows::Forms::Button());
        this->ccFind = (gcnew System::Windows::Forms::Button());
        this->ccAdd = (gcnew System::Windows::Forms::Button());
        this->groupBox1->SuspendLayout();
        this->groupBox2->SuspendLayout();
        this->SuspendLayout();
        // 
        // mainMenu_label
        // 
        this->mainMenu_label->Font = (gcnew System::Drawing::Font(L"Tahoma", 15.75F));
        this->mainMenu_label->Location = System::Drawing::Point(7, 9);
        this->mainMenu_label->Name = L"mainMenu_label";
        this->mainMenu_label->Size = System::Drawing::Size(510, 59);
        this->mainMenu_label->TabIndex = 2;
        this->mainMenu_label->Text = L"Автоматизированная информационная система\r\n«Поиск преступников по отпечаткам паль"
            L"цев»";
        this->mainMenu_label->TextAlign = System::Drawing::ContentAlignment::TopCenter;
        // 
        // profileAdd
        // 
        this->profileAdd->Location = System::Drawing::Point(6, 58);
        this->profileAdd->Name = L"profileAdd";
        this->profileAdd->Size = System::Drawing::Size(95, 25);
        this->profileAdd->TabIndex = 1;
        this->profileAdd->Text = L"Добавить";
        this->profileAdd->UseVisualStyleBackColor = true;
        this->profileAdd->Click += gcnew System::EventHandler(this, &MainMenu::profileAdd_Click);
        // 
        // groupBox1
        // 
        this->groupBox1->Controls->Add(this->profileStat);
        this->groupBox1->Controls->Add(this->profileFind);
        this->groupBox1->Controls->Add(this->profileAdd);
        this->groupBox1->Location = System::Drawing::Point(12, 85);
        this->groupBox1->Name = L"groupBox1";
        this->groupBox1->Size = System::Drawing::Size(107, 120);
        this->groupBox1->TabIndex = 4;
        this->groupBox1->TabStop = false;
        this->groupBox1->Text = L"Личные дела";
        // 
        // profileStat
        // 
        this->profileStat->Location = System::Drawing::Point(6, 89);
        this->profileStat->Name = L"profileStat";
        this->profileStat->Size = System::Drawing::Size(95, 25);
        this->profileStat->TabIndex = 2;
        this->profileStat->Text = L"Статистика";
        this->profileStat->UseVisualStyleBackColor = true;
        // 
        // profileFind
        // 
        this->profileFind->Location = System::Drawing::Point(6, 27);
        this->profileFind->Name = L"profileFind";
        this->profileFind->Size = System::Drawing::Size(95, 25);
        this->profileFind->TabIndex = 0;
        this->profileFind->Text = L"Найти";
        this->profileFind->UseVisualStyleBackColor = true;
        this->profileFind->Click += gcnew System::EventHandler(this, &MainMenu::profileFind_Click);
        // 
        // groupBox2
        // 
        this->groupBox2->Controls->Add(this->ccStat);
        this->groupBox2->Controls->Add(this->ccFind);
        this->groupBox2->Controls->Add(this->ccAdd);
        this->groupBox2->Location = System::Drawing::Point(125, 85);
        this->groupBox2->Name = L"groupBox2";
        this->groupBox2->Size = System::Drawing::Size(107, 120);
        this->groupBox2->TabIndex = 5;
        this->groupBox2->TabStop = false;
        this->groupBox2->Text = L"УГ Дела";
        // 
        // ccStat
        // 
        this->ccStat->Location = System::Drawing::Point(6, 89);
        this->ccStat->Name = L"ccStat";
        this->ccStat->Size = System::Drawing::Size(95, 25);
        this->ccStat->TabIndex = 5;
        this->ccStat->Text = L"Статистика";
        this->ccStat->UseVisualStyleBackColor = true;
        // 
        // ccFind
        // 
        this->ccFind->Location = System::Drawing::Point(6, 27);
        this->ccFind->Name = L"ccFind";
        this->ccFind->Size = System::Drawing::Size(95, 25);
        this->ccFind->TabIndex = 3;
        this->ccFind->Text = L"Найти";
        this->ccFind->UseVisualStyleBackColor = true;
        // 
        // ccAdd
        // 
        this->ccAdd->Location = System::Drawing::Point(6, 58);
        this->ccAdd->Name = L"ccAdd";
        this->ccAdd->Size = System::Drawing::Size(95, 25);
        this->ccAdd->TabIndex = 4;
        this->ccAdd->Text = L"Добавить";
        this->ccAdd->UseVisualStyleBackColor = true;
        this->ccAdd->Click += gcnew System::EventHandler(this, &MainMenu::ccAdd_Click);
        // 
        // MainMenu
        // 
        this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
        this->ClientSize = System::Drawing::Size(529, 366);
        this->Controls->Add(this->groupBox2);
        this->Controls->Add(this->groupBox1);
        this->Controls->Add(this->mainMenu_label);
        this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
        this->MaximizeBox = false;
        this->Name = L"MainMenu";
        this->ShowIcon = false;
        this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
        this->Text = L"Главное меню";
        this->groupBox1->ResumeLayout(false);
        this->groupBox2->ResumeLayout(false);
        this->ResumeLayout(false);

    }
#pragma endregion
private: System::Void profileFind_Click(System::Object^  sender, System::EventArgs^  e) {
    ProfileFind^ formProfileFind;
    formProfileFind = gcnew ProfileFind();
    formProfileFind->setDB(db);
    formProfileFind->Show(this);
}
private: System::Void profileAdd_Click(System::Object^  sender, 
System::EventArgs^  e) {
}
private: System::Void ccAdd_Click(System::Object^  sender, System::EventArgs^  e) {
    CriminalCaseAdd^ ccAdd;
    ccAdd = gcnew CriminalCaseAdd();

    ccAdd->Show(this);
}
};
}

Ошибки:

1>------ Сборка начата: проект: Coursach, Конфигурация: Debug Win32 ------ 1>main.cpp 1>MainMenu.cpp 1>MyForm.cpp 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(197): error C2143: синтаксическая ошибка: отсутствие ";" перед "^" 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(197): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(197): error C2238: непредвиденные лексемы перед ";" 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(26): error C2065: db: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(26): error C2061: синтаксическая ошибка: идентификатор "DataBase" 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(199): error C2065: ProfileFind: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(199): error C2065: formProfileFind: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(200): error C2065: formProfileFind: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(200): error C2061: синтаксическая ошибка: идентификатор "ProfileFind" 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(201): error C2065: formProfileFind: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(201): error C2227: выражение слева от "->setDB" должно указывать на тип класса, структуры или объединения либо на универсальный тип 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(201): note: тип: unknown-type 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(201): error C2065: db: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(202): error C2065: formProfileFind: необъявленный идентификатор 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(202): error C2227: выражение слева от "->Show" должно указывать на тип класса, структуры или объединения либо на универсальный тип 1>c:\users\gintr1k\source\repos\coursach\coursach\MainMenu.h(202): note: тип: unknown-type 1>Создание кода... 1>Сборка проекта "Coursach.vcxproj" завершена с ошибкой. ========== Сборка: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Ошибки возникают в строках:

MainMenu.h(42): private: DataBase ^ db;
MainMenu.h(26): db = gcnew DataBase();
MainMenu.h(200): ProfileFind^ formProfileFind;
MainMenu.h(201): formProfileFind = gcnew ProfileFind();
MainMenu.h(202): formProfileFind->setDB(db);
MainMenu.h(203): formProfileFind->Show(this);

На всякий случай прикладываю код DataBase.h

#pragma once
#include "MainMenu.h"

namespace Coursach
{
    using namespace System;
    using namespace System::Data::SQLite;
    using namespace System::Windows::Forms;
    using namespace System::Text;

    public ref class DataBase
    {
    /* Конструкторы */
    public: DataBase(String^ dbFile)
    {
        db = gcnew SQLiteConnection();

        connect(dbFile);
    }
    public: DataBase()
    {
        DataBase(L"\"coursach.db\"");
    }

    public: ~DataBase()
    {
        db->Close();
    }

    /* Переменные класса */
    private: SQLiteConnection ^ db;

    /*
    Возвращаемые значения:
    0 - Класс инициализирован,
        но не было совершено подключения к БД
    1 - Успешно подключено к БД
    2 - Произошла ошибка при подключении,
        необходимо повторно подключиться (функция connect())
    */

     /* Методы класса */
    public: void connect(String^ dbFile)
    {
        int rowNumb;
        try
        {
            db->ConnectionString = L"Data Source=" + dbFile;
            db->Open();
        }
        catch (Exception ^e) /* Ловим Exception */
        {
            MessageBox::Show(L"Произошла непредвиденная ошибка при попытке подключения к Базе Данных. Ошибка: " + e->ToString(), L"Ошибка подключения к БД");
        }
        try
        {
            SQLiteCommand^ cmdCheckDBTables = db->CreateCommand();
            cmdCheckDBTables->CommandText = L"SELECT COUNT(type) FROM sqlite_master WHERE type='table' AND " +
                L"(name='profiles' OR name='criminal_cases');";
            SQLiteDataReader^ reader = cmdCheckDBTables->ExecuteReader();
            StringBuilder ^sb = gcnew StringBuilder();
            while (reader->Read())
            {
                for (int colCtr = 0; colCtr < reader->FieldCount; ++colCtr)
                {
                    sb->Append(reader->GetValue(colCtr)->ToString());
                }
                sb->AppendLine();
            }
            rowNumb = int::Parse(sb->ToString());
        }
        catch (Exception^ e)
        {
            MessageBox::Show(L"Произошла непредвиденная ошибка при выполнении проверки Базы Данных\r\n\r\nОшибка:" + e->ToString(), L"Ошибка при работе с БД");
        }
        if (rowNumb != 3)
        {
            MessageBox::Show(L"База данных не была обнаружена!!\r\nНовая База Данных будет создана", L"База Данных не обнаружена");
            try
            {
                SQLiteCommand^ cmdDropTables = db->CreateCommand();
                cmdDropTables->CommandText = L"DROP TABLE IF EXISTS [profiles]; DROP TABLE IF EXISTS [criminal_cases];";
                cmdDropTables->ExecuteNonQuery();
            }
            catch (Exception^ e)
            {
                MessageBox::Show(L"Произошла непредвиденная ошибка при создании Базы Данных\r\n\r\nОшибка:" + e->ToString(), L"Ошибка при работе с БД");
            }
            createTable(
                L"CREATE TABLE[profiles](" +
                L"[id] int  NOT NULL" +
                L", [first_name] varchar  NOT NULL" +
                L", [last_name] varchar  NOT NULL" +
                L", [middle_name] varchar  NOT NULL" +
                L", [date_birth] date NOT NULL" +
                L", [registration] varchar  NOT NULL" +
                L", [passport_id] int  NOT NULL" +
                L", [passport_data_of_issue] date NOT NULL" +
                L", [passport_place_of_issue] varchar  NOT NULL" +
                L", CONSTRAINT[sqlite_autoindex_profiles_1] PRIMARY KEY([id])" +
                L");"
            );
        }
    }

    public: SQLiteDataReader^ execSelectQuery(String^ query)
    {
        try
        {
            SQLiteCommand^ cmdSelect = db->CreateCommand();
            cmdSelect->CommandText = query;
            return cmdSelect->ExecuteReader();
        }
        catch (Exception^ e)
        {
            MessageBox::Show(L"Произошла непредвиденная ошибка при создании таблицы Базы Данных\r\n\r\nОшибка:" + e->ToString(), L"Ошибка при работе с БД");
        }
        return nullptr;
    }

    private: void createTable(String^ createCommandtext)
    {
        try
        {
            SQLiteCommand^ cmdCreateTable = db->CreateCommand();

            cmdCreateTable->CommandText = createCommandtext;
            cmdCreateTable->ExecuteNonQuery();
        }
        catch (Exception^ e)
        {
            MessageBox::Show(L"Произошла непредвиденная ошибка при создании таблицы Базы Данных\r\n\r\nОшибка:" + e->ToString() + L"\r\n---------------\r\nКоманда:\r\n" + createCommandtext, L"Ошибка при работе с БД");
        }
    }
    };
}

Проблема 2:

Поскольку я не силен в C++, то хотелось бы уточнить как можно между двумя формами передать объект класса?

К примеру, в главной форме (приложил код) создаю объект db класса DataBase и необходимо передать данный объект другой форме для того, чтобы можно было работать с БД. Каким образом это лучше сделать и стоит ли вообще так поступать?

P.S. в коде, что я приложил, есть объект БД, но он нигде не используется кроме как для передачи в другую форму. Хотел сделать пару фич на главной форме, но пока что не до них из-за ошибок выше.

1 ответ 1

0

Из DataBase.h надо убрать #include "MainMenu.h" и все заработает.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.