0

Не доходит как правильно "рассовать" написанный мной код. Возможно ошибка связана с fstream?

Файл main.cpp

#include "stdafx.h"
#include "Steck.h"

int main()
{
    setlocale(LC_ALL, "Russian");
    file.open("Text.txt");
    if (!file.is_open())
    {
        cout << "Файл не найден!";
        _getch();
        return 1;
    }
    Stack1 *st1;
    Stek2 *st2;
    bool done = false;
    int temp;

    while (!done)
    {
        switch (menu())
        {
        case 1: 
            st1->file_input_push_ch(st1);
            st2->file_input_push_nech(st2);
            break;
        case 2:
            cout << endl << "Номер состава:";
            cin >> temp;
            if (temp % 2 == 0)
                st1->push_ch(st1, temp);
            else
                st2->push_nech(st2,temp);
            cout << endl;
            break;
        case 3:
            st1->print_ch(st1);
            st2->print_nech(st2);
            break;
        case 4:
            cout << "  Конец работы. " << endl;
            done = true;
            break;
        default:
            cout << endl << " Внимание!!!  Вводите только цифры от 1-го до 4-ёх!" << endl;
            break;
        }
    }

    _getch();
    return 0;
}

Файл Steck.h

#pragma once
#ifndef FILENAME_H
#define FILENAME_H
#include <fstream>
#include <iostream>
#include <conio.h>

using std::ifstream;
using std::cout;
using std::cin;
using std::endl;

ifstream file;

int menu();
class Stack1
{
public:
    Stack1() :ch(0), next(0)
    {
        cout << endl << "Constructor1 working..." << endl;
    }
    ~Stack1();
    void push_ch(Stack1*&, int);
    void file_input_push_ch(Stack1*&);
    void print_ch(Stack1*);
private:
    int ch;
    Stack1 *next;
};

class Stek2
{
public:
    Stek2() :nech(0), next(0) 
    {
        cout << endl << "Constructor2 working..." << endl;
    }
    void push_nech(Stek2*&, int);
    void file_input_push_nech(Stek2*&);
    void print_nech(Stek2*);
    ~Stek2();

private:
    int nech;
    Stek2 *next;
};


#endif // !FILENAME_H

И файл Stack.cpp

#include "stdafx.h"
#include "Steck.h"

int menu()
{
    char buf[10];
    int option;
    do
    {
        cout << endl << "1 - Ввести данные с файла." << endl;
        cout << endl << "2 - Ввести данные вручную." << endl;
        cout << endl << "3 - Вывести состояние сортировочного узла" << endl;
        cout << endl << "4 -  Выход из программы." << endl;
        cin >> buf; option = atoi(buf);
    } while (!option);
    cin.get();
    return option;
}

void Stack1::push_ch(Stack1 *&next, int temp)
{
    Stack1 *pv = new Stack1;
    if (temp % 2 == 0)
    {
        pv->ch = temp;
        pv->next = next;
        next = pv;
    }
    else
        delete pv;
}

void Stack1::file_input_push_ch(Stack1 *&next)
{

    int temp;
    while (!file.eof())
    {
        file >> temp;
        push_ch(next, temp);
    }
}

void Stack1::print_ch(Stack1 *b)
{
    Stack1 *print = b;
    if (print == NULL)
        cout << endl << " Чётных нет. " << endl;
    else
    {
        cout << endl << "Чётные номера: " << endl;
        while (print)
        {
            cout << print->ch << "  ";
            print = print->next;
        }
         cout << endl;
    }
}

Stack1::~Stack1()
{
    cout << endl << "Destructor1 working..." << endl;
    while (next)
    {
        Stack1 *p;
        p = next;
        next = next->next;
        delete p;
    }
}

void Stek2::push_nech(Stek2 *&next, int temp)
{
    Stek2 *pv = new Stek2;
    if (temp % 2 != 0)
    {
        pv->nech = temp;
        pv->next = next;
        next = pv;
    }
    else
        delete pv;
}

void Stek2::file_input_push_nech(Stek2 *&next)
{
    int temp;
    while (!file.eof())
    {
        file >> temp;
        push_nech(next, temp);
    }
}

void Stek2::print_nech(Stek2 *b)
{
    Stek2 *print;
    print = b;
    if (print == NULL)
        cout << endl << " Нечетных нет. " << endl;
    else
    {
        cout << endl << "Нечётные номера: " << endl;
        while (print)
        {
            cout << print->nech << " ";
            print = print->next;
        }
        cout << endl;
    }
}

Stek2::~Stek2()
{
    cout << endl << "Destructor2 working..." << endl;
    while (next)
    {
        Stek2 *p;
        p = next;
        next = next->next;
        delete p;
    }
}

Пытаюсь "построить" выдаёт следующее:

Ошибка LNK2005 "class std::basic_ifstream<char,struct
std::char_traits > file" (?file@@3V?$basic_ifstream@DU? $char_traits@D@std@@@std@@A) уже определен в Stack.obj Классы_вариант_1 C:\Users\Семён\Documents\Visual Studio 2015\Projects\Классы_вариант_1\Классы_вариант_1\Классы_вариант_1.obj 1

Ошибка LNK1169 обнаружен многократно определенный символ - один или более Классы_вариант_1 C:\Users\Семён\Documents\Visual Studio
2015\Projects\Классы_вариант_1\Debug\Классы_вариант_1.exe 1

Может у кого-нибудь был опыт? Отпишитесь.

1 ответ 1

1

ifstream file; в .h-файле. Правило одного определения нарушено.

Мне вообще не нравится идея делать file глобальной переменной - но как минимум в .h-файле объявите как

extern ifstream file;

ну, а в каком-то .cpp-файле уже определяйте

ifstream file;

Но! честное слово, пересмотрите решение так, чтоб глобальных переменных не было.

2
  • Сделал, как Вы сказали. Заработало! 28 сен 2016 в 17:15
  • Да, еще одну ошибку нашел! В main объектам Stack1 *st1 и Stek2 *st2 надо присвоить NULL, иначе не будет работать функции просмотра. 28 сен 2016 в 17:43

Ваш ответ

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

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