ошибка: переопределение класса TextDocsCmpr

0

Сожалею! У меня есть еще один вопрос. Это моя первая ошибка, с которой я пытаюсь работать.

Я получаю ошибку в определении класса моего заголовочного файла PlagiarismDetector.h:

#include <vector>  // std::vector
#include <string> // std::string
#include <fstream> // std::ifstream
#include <set> // std::set

class TextDocsCmpr { 

public: 
    TextDocsCmpr(); 
    ~TextDocsCmpr(); 
    void addFile(std::string); 
    void setThreshold(double); 

private:
    std::vector<std::string> files_vec; 
    std::vector<std::string> get_file_sntncs(std::fstream&);
    std::vector<std::string> get_sntnc_wrds(const std::string&);
    double sntnc_smlrty_qtnt(std::vector<std::string>, std::vector<std::string>);
    static std::set<char> LETTERS_SET;
    double sntnc_smlrty_thrshld; 
    static const double SNTNC_SMLRTY_THRSHLD_DEFAULT = 0.5;         
};

Я не могу понять, почему он говорит, что я пытаюсь переопределить его. Соответствующий файл cpp:

#include "PlagiarismDetector.h"


#include <iostream> // std::cout, std::endl
#include <algorithm> // std::swap
#include <map> // std::map

// ------------------------------------ TextDocsCmpr class member functions -----------------------------------------

// ---------- Public functions ------------

// Default constructor
TextDocsCmpr::TextDocsCmpr() { 
    // Set the sentence similarity threshold to its default value
    sntnc_smlrty_thrshld = SNTNC_SMLRTY_THRSHLD_DEFAULT;
    // Add all the characters of LETTERS_ARR to LETTERS_SET
    const char LETTERS_ARR[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
                                'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
                                'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 
                                'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '\'', '.'}; 
    for (int i = 0; i < sizeof(LETTERS_ARR)/sizeof(char); ++i)
        LETTERS_SET.insert(LETTERS_ARR[i]);
}


// Trivial destructor
TextDocsCmpr::~TextDocsCmpr() {}

// Add file to files_vec (if file is found)
void TextDocsCmpr::addFile(std::string filename) { 
        files_vec.push_back(filename);
} 

// Sets the sentence comparison threshold value
void TextDocsCmpr::setThreshold(double t) { 
    if (t < 0 || t > 1) {
        // Print error for now. Will change to an error window later.
        std::cout << "Threshold not changed. Must be bewteen 0 and 1 inclusive" << std::endl;
    } else { 
        sntnc_smlrty_thrshld = t; 
    }
}


// ---------- Private functions --------------

// Extract sentences from Plain Text file 
std::vector<std::string> TextDocsCmpr::get_file_sntncs(std::fstream& file) { 
    // The sentences will be stored in a vector of strings, strvec:
    std::vector<std::string> strvec; 
    // Print out error if the file could not be found: 
    if(file.fail()) {
        std::cout << "Could not find the file. :( " << std::endl;
        // Otherwise, proceed to add the sentences to strvec:
    } else { 
        char curchar;
        std::string cursentence;
        /* While we haven't reached the end of the file, add the current character to the 
         string representing the current sentence. If that current character is a period, 
         then we know we've reached the end of a sentence if the next character is a space,  
         a quotation mark (to denote the end of a quoted sentence), a new line character or
         if there is no next character; and we must then add the current sentence to strvec. */
        while (file >> std::noskipws >> curchar) { 
            cursentence.push_back(curchar);
            if (curchar == '.') {
                if (file >> std::noskipws >> curchar) { 
                    if (curchar == ' ' || curchar == '"' || curchar == '\n') {
                        strvec.push_back(cursentence);
                        cursentence.clear();
                    } else { 
                        cursentence.push_back(curchar);
                    }
                } else { 
                    strvec.push_back(cursentence);
                    cursentence.clear();
                }

            }

        }

    }
    return strvec; 
} 

std::vector<std::string> TextDocsCmpr::get_sntnc_wrds(const std::string& S) { 
    // The words of the sentence will be stored as a vector of strings and returned.
    std::vector<std::string> retvec;
    std::string::const_iterator it = S.begin(); 
    while (it != S.end()) { 
        if (LETTERS_SET.count(*it) == 1) { 
            /* We've found a letter. Now let us place all the consecutive letters
             into a string which will be added to our vector of strings, retvec. */
            std::string str(1,*it);
            int k(0);
            while (((it+k+1) != S.end()) && (LETTERS_SET.count(*(it+k+1)) == 1)) {  
                str.push_back(*(it + (++k)));
            }
            retvec.push_back(str);
            it += (k+1);
        }
        else { 
            // Or if we didn't find a letter, advance the iterator the unit. 
            ++it;
        }
    }
    return retvec;
} 

double TextDocsCmpr::sntnc_smlrty_qtnt(std::vector<std::string> S1, std::vector<std::string> S2) {
    // Force s1 to be the smaller sentence.
    if (S1.size() > S2.size())
        swap(S1, S2);
    // Add all the words of s1 to a set.
    std::set<std::string> wordset; 
    for (std::vector<std::string>::const_iterator it = S1.begin(); it != S1.end(); ++it) 
        wordset.insert(*it);
    // Save the number of unique words in s1.
    int oldsize = wordset.size(); 
    // Add the words of s2 to the set.
    for (std::vector<std::string>::const_iterator it = S2.begin(); it != S2.end(); ++it) 
        wordset.insert(*it);
    /* The difference between oldsize and the current size of wordset is the number of words in
     s2 which are not in s1. Therefore the proportion of words of s1 contained in s2 is oldsize/wordset.size(). 
     This is the sentence similarity quotient which is returned. */
    return (double)oldsize/(double)wordset.size();
}

// ----------------------------------------------------------------------------------------------------------
Теги:

2 ответа

1

Вероятно, вы, вероятно, включаете PlagiarismDetector.h несколько раз в одном исходном файле, возможно, косвенно через другой заголовочный файл.

Для защиты от этого следует использовать защитные устройства.

0

Если вы включаете заголовочные файлы несколько раз. Чтобы упростить задачу, попробуйте добавить

#pragma once

в ваших файлах заголовков. Это предотвратит множественное включение.


Существуют и другие методы, но это я считаю простейшим. И почти все современные компиляторы поддерживают это. Вы можете увидеть здесь

Ещё вопросы

Сообщество Overcoder
Наверх
Меню