首页 > 解决方案 > 当我声明它时,Class' 没有被声明为错误

问题描述

我正在制作一个可以做随机事情的小外壳。Bt 每当我编译时我都会收到错误'Shell' has not been declared

我在 main.cpp 中声明了类 shell 和对象,我已经找了一段时间了,什么也没有。我是 oop 新手,所以这可能很愚蠢,但我已经知道了

我正在使用 3 个文件

主.cpp:

#include <iostream>
#include "shell/shell.cpp"


int main ()
{
 Shell shl;
 while (!shl.exitTime())
 {
     std::cin.ignore();
     shl.putIn(std::getline(std::cin));
 }

}

/shell/shell.cpp:

#include <vector>
#include "shell.h"


class Shell {

private:
    std::string in;
    bool exitBool;

public:
    // Functions
    void clear();
    void print(std::string inp);
    void println(std::string inp);
    void putIn(std::string inp);
    std::string input();
    bool exitTime();

Shell()
{
    exitBool = false;
}


};

和 /shell/shell.h:

 #include <vector>


void Shell::print(std::string inp)
{
std::cout << inp;
}

void Shell::println(std::string inp)
{
std::cout << inp << std::endl;
} 

void Shell::putIn(std::string inp)
{
inp = in;
}

std::string Shell::input()
{
return in;
} 

bool exitTime()
{
return exitBool;
}

标签: c++oop

解决方案


你应该

  • 在文件中编写类函数的定义。.cpp
  • 在文件中编写类函数的声明。.h
  • 包括.h文件。

你真的做到了

  • 在文件中编写类函数的定义。.h
  • 在文件中编写类函数的声明。.cpp
  • 包括.cpp文件。

尝试这个:

主.cpp:

#include <iostream>
#include "shell/shell.h"


int main ()
{
 Shell shl;
 while (!shl.exitTime())
 {
     std::cin.ignore();
     shl.putIn(std::getline(std::cin));
 }

}

/shell/shell.cpp:

#include <vector>
#include "shell.h"

void Shell::print(std::string inp)
{
std::cout << inp;
}

void Shell::println(std::string inp)
{
std::cout << inp << std::endl;
} 

void Shell::putIn(std::string inp)
{
inp = in;
}

std::string Shell::input()
{
return in;
} 

bool exitTime()
{
return exitBool;
}

和 /shell/shell.h:

#include <vector>
#include <string>

class Shell {

private:
    std::string in;
    bool exitBool;

public:
    // Functions
    void clear();
    void print(std::string inp);
    void println(std::string inp);
    void putIn(std::string inp);
    std::string input();
    bool exitTime();

Shell()
{
    exitBool = false;
}


};

推荐阅读