我有一个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
我做错了什么?我做的事情不是必要的吗?
答案 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的网站。