标识符未定义的C ++即使我有CPP和Header文件

时间:2017-01-04 04:13:53

标签: c++ header-files

我有一个main.cpp文件以及main.cpp中包含的一堆其他cpp文件和头文件。在标头文件中,我在正确的位置使用了#indef#define#endif,并且还在main.cpp中包含了头文件。但是,当我尝试使用我在主文件中创建的函数时,它会给我一个错误“Identifier(function_name)undefined”。

例如:

//main.cpp
#include "example.h"

int main(){
foo();

//example.cpp
example::foo(){
     //code
}

//example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H

class example{
int foo();
}
#endif

我做错了什么?我做的事情不是必要的吗?

1 个答案:

答案 0 :(得分:2)

调用foo();会导致此错误。要调用example::foo函数,您需要一个example类型的对象。像这样:

int main() {
    example ex;
    ex.foo();
}

您还必须公开foo方法,以便main可以使用它:

class example {
public:
    void foo();
};

示例:

假设我有以下程序:

void foo() { // #1
    // typetype codecode;
}

class Example {
public:
    void foo();
};

Example::foo() { // #2
    // typetype codecode;
}

int main() {
    Example ex;

    foo(); // #1 gets called
    ex.foo(); // #2 gets called on object ex
}

更多信息:

为了更好地理解这种事情,你应该学习面向对象的编程和类。 OOP的解释包括以下网站:

我相信你可以找到更多关于OOP的网站。