Ошибка C ++: переменная не называет тип при попытке доступа к глобальным переменным - PullRequest
0 голосов
/ 19 апреля 2020

В программе, которую я пишу, у меня есть 3 файла. main, функции и заголовочный файл. В основном файле используется заголовок #include «реализация. cpp», а в файле функций используется заголовок #include «driver.h». В файле реализации 3 были объявлены структуры, каждая из которых делится своими значениями с помощью extern, что также можно увидеть в минимально необходимом коде воспроизведения. В заголовочном файле я объявил 3 переменные, чтобы использовать эти внешние переменные. Я полагал, что этого было достаточно, чтобы решить мою проблему, но проблема все еще остается. Когда мой код пытается скомпилировать, я получаю следующие сообщения об ошибках. Их много, но я считаю, что все они проистекают из одной и той же проблемы. Эта проблема заключается в том, что файл заголовка может найти типы Customer, Parts и Builder

In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:7:1: error: 'Customer' does not name a type
    7 | Customer myCustomer;
      | ^~~~~~~~
driver.h:8:1: error: 'Builder' does not name a type
    8 | Builder myBuilder;
      | ^~~~~~~
driver.h:9:1: error: 'Part' does not name a type
    9 | Part myPart;
      | ^~~~
driver.h:14:13: error: 'Part' was not declared in this scope
   14 | std::vector<Part> readpartFile();
      |             ^~~~
driver.h:14:17: error: template argument 1 is invalid
   14 | std::vector<Part> readpartFile();
      |                 ^
driver.h:14:17: error: template argument 2 is invalid
driver.h:16:13: error: 'Customer' was not declared in this scope
   16 | std::vector<Customer> readcustomerFile();
      |             ^~~~~~~~
driver.h:16:21: error: template argument 1 is invalid
   16 | std::vector<Customer> readcustomerFile();
      |                     ^
driver.h:16:21: error: template argument 2 is invalid
driver.h:18:13: error: 'Builder' was not declared in this scope
   18 | std::vector<Builder> readbuilderFile();
      |             ^~~~~~~
driver.h:18:20: error: template argument 1 is invalid
   18 | std::vector<Builder> readbuilderFile();
      |                    ^
driver.h:18:20: error: template argument 2 is invalid
driver.h:20:24: error: 'Customer' does not name a type
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                        ^~~~~~~~
driver.h:20:55: error: 'Part' was not declared in this scope
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                                                       ^~~~
driver.h:20:59: error: template argument 1 is invalid
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                                                           ^
driver.h:20:59: error: template argument 2 is invalid
driver.h:22:40: error: 'Part' was not declared in this scope
   22 | void robotComplexity(const std::vector<Part>& vecB, const std::vector<Customer>& vecC);
      |                                        ^~~~
driver.h:22:44: error: template argument 1 is invalid
   22 | void robotComplexity(const std::vector<Part>& vecB, const std::vector<Customer>& vecC);
      |                                            ^
driver.h:22:44: error: template argument 2 is invalid
driver.h:22:71: error: 'Customer' was not declared in this scope
   22 | void robotComplexity(const std::vector<Part>& vecB, const std::vector<Customer>& vecC);
      |                                                                       ^~~~~~~~
driver.h:22:79: error: template argument 1 is invalid
   22 | void robotComplexity(const std::vector<Part>& vecB, const std::vector<Customer>& vecC);
      |                                                                               ^
driver.h:22:79: error: template argument 2 is invalid
driver.h:24:38: error: 'Customer' was not declared in this scope
   24 | double variability(const std::vector<Customer>& customerList, const std::vector<Builder>& builderList);
      |                                      ^~~~~~~~
driver.h:24:46: error: template argument 1 is invalid
   24 | double variability(const std::vector<Customer>& customerList, const std::vector<Builder>& builderList);
      |                                              ^
driver.h:24:46: error: template argument 2 is invalid
driver.h:24:81: error: 'Builder' was not declared in this scope
   24 | double variability(const std::vector<Customer>& customerList, const std::vector<Builder>& builderList);
      |                                                                                 ^~~~~~~
driver.h:24:88: error: template argument 1 is invalid
   24 | double variability(const std::vector<Customer>& customerList, const std::vector<Builder>& builderList);
      |                                                                                        ^
driver.h:24:88: error: template argument 2 is invalid
driver.h:26:34: error: 'Builder' was not declared in this scope
   26 | std::vector<double> buildAttempt(Builder b, double variaiblity, double complexityRobot);
      |                                  ^~~~~~~
driver.h:26:45: error: expected primary-expression before 'double'
   26 | std::vector<double> buildAttempt(Builder b, double variaiblity, double complexityRobot);
      |                                             ^~~~~~
driver.h:26:65: error: expected primary-expression before 'double'
   26 | std::vector<double> buildAttempt(Builder b, double variaiblity, double complexityRobot);
      |                                                                 ^~~~~~
In file included from driver.cpp:4:
implementation.cpp:43:19: error: ambiguating new declaration of 'std::vector<Part> readpartFile()'
   43 | std::vector<Part> readpartFile() //function to read Builders, Customers and Parts text file
      |                   ^~~~~~~~~~~~
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:14:19: note: old declaration 'int readpartFile()'
   14 | std::vector<Part> readpartFile();
      |                   ^~~~~~~~~~~~
In file included from driver.cpp:4:
implementation.cpp:77:23: error: ambiguating new declaration of 'std::vector<Customer> readcustomerFile()'
   77 | std::vector<Customer> readcustomerFile()
      |                       ^~~~~~~~~~~~~~~~
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:16:23: note: old declaration 'int readcustomerFile()'
   16 | std::vector<Customer> readcustomerFile();
      |                       ^~~~~~~~~~~~~~~~
In file included from driver.cpp:4:
implementation.cpp:100:22: error: ambiguating new declaration of 'std::vector<Builder> readbuilderFile()'
  100 | std::vector<Builder> readbuilderFile()
      |                      ^~~~~~~~~~~~~~~
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:18:22: note: old declaration 'int readbuilderFile()'
   18 | std::vector<Builder> readbuilderFile();
      |                      ^~~~~~~~~~~~~~~
In file included from driver.cpp:4:
implementation.cpp:208:81: error: 'std::vector<double> buildAttempt(Builder, double, double)' redeclared as different kind of entity
  208 | vector<double>buildAttempt(Builder b, double variaiblity, double complexityRobot) {
      |                                                                                 ^
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:26:21: note: previous declaration 'std::vector<double> buildAttempt'
   26 | std::vector<double> buildAttempt(Builder b, double variaiblity, double complexityRobot);
      |                     ^~~~~~~~~~~~
In file included from driver.cpp:4:
implementation.cpp: In function 'std::vector<double> buildAttempt(Builder, double, double)':
implementation.cpp:230:23: error: no matching function for call to 'complexity(Customer&, int&)'
  230 |  complexity(c,partsVec);
      |                       ^
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:20:7: note: candidate: 'float complexity(const int&, const int&)'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |       ^~~~~~~~~~
driver.h:20:34: note:   no known conversion for argument 1 from 'Customer' to 'const int&'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                  ~~~~~~~~~~~~~~~~^
In file included from driver.cpp:4:
implementation.cpp:138:7: note: candidate: 'float complexity(const Customer&, const std::vector<Part>&)'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |       ^~~~~~~~~~
implementation.cpp:138:62: note:   no known conversion for argument 2 from 'int' to 'const std::vector<Part>&'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |                                     ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
implementation.cpp:243:23: error: no matching function for call to 'complexity(Customer&, int&)'
  243 |  complexity(c,partsVec);
      |                       ^
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:20:7: note: candidate: 'float complexity(const int&, const int&)'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |       ^~~~~~~~~~
driver.h:20:34: note:   no known conversion for argument 1 from 'Customer' to 'const int&'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                  ~~~~~~~~~~~~~~~~^
In file included from driver.cpp:4:
implementation.cpp:138:7: note: candidate: 'float complexity(const Customer&, const std::vector<Part>&)'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |       ^~~~~~~~~~
implementation.cpp:138:62: note:   no known conversion for argument 2 from 'int' to 'const std::vector<Part>&'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |                                     ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
driver.cpp: In function 'int main()':
driver.cpp:24:27: error: no matching function for call to 'complexity(Customer&, int&)'
   24 |     complexity(c, partsVec);
      |                           ^
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:20:7: note: candidate: 'float complexity(const int&, const int&)'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |       ^~~~~~~~~~
driver.h:20:34: note:   no known conversion for argument 1 from 'Customer' to 'const int&'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                  ~~~~~~~~~~~~~~~~^
In file included from driver.cpp:4:
implementation.cpp:138:7: note: candidate: 'float complexity(const Customer&, const std::vector<Part>&)'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |       ^~~~~~~~~~
implementation.cpp:138:62: note:   no known conversion for argument 2 from 'int' to 'const std::vector<Part>&'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |                                     ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
driver.cpp:26:53: error: no matching function for call to 'complexity(Customer&, int&)'
   26 |     writeFile(buildAttempt(b, complexity(c, partsVec), variability(customerVec, builderVec)));
      |                                                     ^
In file included from implementation.cpp:8,
                 from driver.cpp:4:
driver.h:20:7: note: candidate: 'float complexity(const int&, const int&)'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |       ^~~~~~~~~~
driver.h:20:34: note:   no known conversion for argument 1 from 'Customer' to 'const int&'
   20 | float complexity(const Customer& c, const std::vector<Part>& parts);
      |                  ~~~~~~~~~~~~~~~~^
In file included from driver.cpp:4:
implementation.cpp:138:7: note: candidate: 'float complexity(const Customer&, const std::vector<Part>&)'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |       ^~~~~~~~~~
implementation.cpp:138:62: note:   no known conversion for argument 2 from 'int' to 'const std::vector<Part>&'
  138 | float complexity(const Customer& c, const std::vector<Part>& parts)
      |                                     ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~

Ниже приведен минимальный объем кода, необходимый для воспроизведения этой ошибки. Для удобства я только собираюсь включить соответствующий код в Part, так как базовый код для заказчика и строителя такой же

мой основной файл


#include <iostream>
#include <string>
#include "implementation.cpp"
#include <fstream>
#include <vector> 
#include <random>
using namespace std;

int main()
{
    Part p;
    auto partsVec =  readpartFile();return 0;
}

мой заголовочный файл


#include <vector>
#include <string>
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE


std::vector<Part> readpartFile();

#endif

С этого момента отмечается, что программа не распознает Part myPart, поэтому объявление вектора как типа Part не работает. В связи с этим происходят эти ошибки.

driver.h:9:1: error: 'Part' does not name a type
    9 | Part myPart;
      | ^~~~
driver.h:14:13: error: 'Part' was not declared in this scope
   14 | std::vector<Part> readpartFile();
      |             ^~~~

Наконец, вот файл реализации с кодом, соответствующим части 1. 1015 *

#include <iostream>
#include <string>
#include <sstream> 
#include <fstream>
#include <algorithm> 
#include "driver.h"
#include <random>
#include <vector>
#include <time.h>
using namespace std;

struct Part {
char partCode;
std::string partName;
int maximum;
int minimum;
int complexity;
};
extern Part myPart;

std::ifstream partsList("Parts.txt");


std::vector<Part> readpartFile() //function to read Builders, Customers and Parts text file
{
    std::vector<Part> parts;
    std::string line;

    while (std::getline(partsList, line))
    {
        line.pop_back(); //removing '.' at end of line
        std::string token;
        std::istringstream ss(line);
        Part part;

        std::getline(ss, token, ':');
        part.partCode = token[0];
        std::getline(ss, part.partName, ':');
        std::getline(ss, token, ':');
        part.minimum = std::stoi(token);
        std::getline(ss, token, ':');
        part.maximum = std::stoi(token);
        std::getline(ss, token, ':');
        part.complexity = std::stoi(token);
        parts.push_back(std::move(part));
    }

    return parts;
    }

Этого кода должно быть достаточно, чтобы предоставить кому-либо средства для выяснения моей проблемы и возможного ее устранения. , Спасибо

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

Ответы [ 3 ]

1 голос
/ 19 апреля 2020

Ваш заголовочный файл должен выглядеть следующим образом

#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE

#include <vector>
#include <string>

struct Part {
    char partCode;
    std::string partName;
    int maximum;
    int minimum;
    int complexity;

};
extern Part myPart;

std::vector<Part> readpartFile();

#endif

Ваш основной файл должен выглядеть следующим образом

#include <iostream>
#include <string>
#include <fstream>
#include <vector> 
#include <random>
#include "myheaderfile.h" // sorry I don't know what your header file is really called
using namespace std;

int main()
{
    Part p;
    auto partsVec =  readpartFile();return 0;
}

Ваш файл реализации должен выглядеть следующим образом

#include <iostream>
#include <string>
#include <sstream> 
#include <fstream>
#include <algorithm> 
#include "myheaderfile.h" // sorry I don't know what your header file is really called
#include <random>
#include <vector>
#include <time.h>
using namespace std;

std::vector<Part> readpartFile() //function to read Builders, Customers and Parts text file
{
    std::ifstream partsList("Parts.txt");

    ...
}
1 голос
/ 19 апреля 2020

Реструктурированный.

driver.h

#ifndef DRIVER_H
#define DRIVER_H

#include <string>
#include <vector>

struct Part {                      // class definition
    char partCode;
    std::string partName;
    int maximum;
    int minimum;
    int complexity;
};

std::vector<Part> readpartFile();  // (extern) forward declaration of a function

#endif

реализация. cpp

// only include what you use:

#include "driver.h"

//#include <algorithm>  // why?
#include <fstream>
//#include <iostream>   // why?
//#include <random>     // why?
#include <sstream>
#include <string>
#include <vector>
//#include <time.h>     // why?

// using namespace std; // don't

std::vector<Part>
readpartFile() // function to read Builders, Customers and Parts text file
{
    std::ifstream partsList("Parts.txt"); // don't make this global
    std::vector<Part> parts;
    std::string line;

    while(std::getline(partsList, line)) {
        line.pop_back(); // removing '.' at end of line
        std::string token;
        std::istringstream ss(line);
        Part part;

        std::getline(ss, token, ':');
        part.partCode = token[0];
        std::getline(ss, part.partName, ':');
        std::getline(ss, token, ':');
        part.minimum = std::stoi(token);
        std::getline(ss, token, ':');
        part.maximum = std::stoi(token);
        std::getline(ss, token, ':');
        part.complexity = std::stoi(token);
        parts.push_back(std::move(part));
    }

    return parts;
}

main. cpp

#include "driver.h" // not implementation.cpp

// unused header files removed

int main() {
    Part p;
    auto partsVec = readpartFile();
}

Компиляция - без заголовочных файлов, только .cpp файлов:

g++ -Wall -Wextra -pedantic -pedantic-errors main.cpp implementation.cpp -o program
0 голосов
/ 19 апреля 2020

Кажется, у вас есть ряд недоразумений при выпуске того, что вы вставляете в cpp -файлы и что вы помещаете в заголовочные файлы.

Но для начала - не включайте cpp файлы! Это заголовочный файл, который вы должны включить.

Так же, как и

#include "implementation.h"  // instead of implementation.cpp

В файле реализаций .h должно быть определение структуры Part. Так что переместите его из файла cpp в файл заголовка. Например:

creation.h

#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE

#include <vector>
#include <string>

struct Part {
    char partCode;
    std::string partName;
    int maximum;
    int minimum;
    int complexity;
};


std::vector<Part> readpartFile();

#endif

И затем вы включаете заголовочный файл в реализацию. cpp

реализация. cpp

#include <iostream>
#include <string>
#include <sstream> 
#include <fstream>
#include <algorithm> 
#include "driver.h"
#include <random>
#include <vector>
#include <time.h>

#include "implementation.h"  // Notice

using namespace std;


std::vector<Part> readpartFile() 
{
    ...
}

и вы также включаете его в другие файлы, которым необходимо использовать структуру Part

...