【问题标题】:Codeblocks: 'Class' was not declared in this scope代码块:“类”未在此范围内声明
【发布时间】:2016-02-08 03:32:55
【问题描述】:

所以我正在尝试编译一个非常简单的项目。由于某些原因,它在 .cpp 文件中找不到我的课程。

代码如下: main.cpp:

#include <iostream>
#include "Dog.h"

using namespace std;


int main()
{
    Dog myDog;
    return 0;
}

狗.h:

#ifndef DOG_H
#define DOG_H


class Dog
{
    public:
        Dog();
        virtual ~Dog();
        Dog(const Dog& other);
        Dog& operator=(const Dog& other);
    protected:
    private:
};

#endif // DOG_H

狗.cpp:

#include "Dog.h"

Dog::Dog()
{
    //std::cout << "I'm alive!";
}

Dog::~Dog()
{
    //dtor
}

Dog::Dog(const Dog& other)
{
    //copy ctor
}

Dog& Dog::operator=(const Dog& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

所以这是非常基本的,但我仍然收到错误:'Dog' is not declared in this scope.

我认为我需要将其添加到构建中,但我已经通过右键单击项目窗口中的 dog.cpp 并构建设置来做到这一点。

编译器日志:

-------------- Build: Debug in MyProject (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g -Iinclude -c C:\Users\tamas\Documents\MyProject\include\Dog.cpp -o obj\Debug\include\Dog.o
mingw32-g++.exe -Wall -fexceptions -g -Iinclude -c C:\Users\tamas\Documents\MyProject\main.cpp -o obj\Debug\main.o
C:\Users\tamas\Documents\MyProject\main.cpp: In function 'int main()':
C:\Users\tamas\Documents\MyProject\main.cpp:9:5: error: 'Dog' was not declared in this scope
     Dog myDog;
     ^
C:\Users\tamas\Documents\MyProject\main.cpp:9:9: error: expected ';' before 'myDog'
     Dog myDog;
         ^

【问题讨论】:

  • include "Dog.h" 我认为这是复制/粘贴错误。
  • 是的,# 字符确实存在!
  • what 范围内到底 Dog 没有被定义? (编译器应该告诉你的)
  • 如果 Dog.cpp 不在构建中,我怀疑您会遇到未解决的外部符号错误。
  • 不,Dog.cpp 不是问题。 Dog.h 是问题所在 - 然而,它的内容似乎还不错。所以你正在编译一些其他的 Dog.h。

标签: c++ codeblocks mingw32


【解决方案1】:

您在问题中发布的代码没有任何问题。

几个cmets:

  • #include &lt;iostream&gt; 添加到Dog.cpp,这样您就可以在Dog() 构造函数中取消注释cout 调用
  • 您可能会通过在 main.cpp 中注释掉 #include "Dog.h" 来导致错误
    • 这会阻止编译器知道“狗”是什么
  • 导致错误的另一种方法是,如果正在定义 DOG_H,则:
    • 手动作为编译器选项。 (确保它没有被定义)
    • 手动通过额外的#define
    • 自动通过其他一些标题。确保您没有不小心将DOG_H 复制到另一个头文件中。 (如果您的编译器支持使用非标准 #pragma once,您可以使用它来代替包含防护)

【讨论】:

  • 据我所知,这不是答案。
  • #include 没有被注释掉,我也删除了#IFNDEF 和它的对应行。但是检查编译器日志,也许就是错误所在?
  • @user2315991 DOG_H 不是手动定义的,也不是在 `#include "Dog.h" 之前定义的,对吗?
【解决方案2】:

问题在于正确的 Dog.h 文件位于应该在的其他位置(在 include/ 目录中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2012-06-15
    • 1970-01-01
    • 2021-09-20
    • 2016-08-09
    相关资源
    最近更新 更多