[英]Separating the code in header.h, main.cpp and implementation.cpp
[英]Function not declared in scope / How use header.h, header.cpp, and main.cpp together?
我在C ++的一个初学者,我遇到了麻烦在宣布我的功能header.h
文件中定义header.cpp
,并呼吁在main.cpp
。 我一直在寻找解决方案,但我似乎无济于事。 对于如何解决这些问题,我将不胜感激。
这是我的代码:
main.cpp
#include <iostream>
#include "DLinkedList.h"
int main() {
getInfo(); //Running my function getInfo
}
DLinkedList.h
#ifndef DLINKEDLIST_H
#define DLINKEDLIST_H
class Node
{
private:
int info;
public:
Node* prev;
Node* next;
int getInfo(); //Declaring my function getInfo
void setInfo(int value);
};
#endif
DLinkedList.cpp
#include <iostream>
#include "DLinkedList.h"
int getInfo() { //Defining my function getInfo
int answer;
std::cout << "Input the integer you want to store in the node: ";
std::cin >> answer;
return answer;
}
和错误消息:
exit status 1
main.cpp: In function 'int main()':
main.cpp:6:3: error: 'getInfo' was not declared in this scope
getInfo();
^~~~~~~
getInfo()
不是自由函数。 它是Node
类的成员函数。 因此,它需要像这样与它所属的使用范围解析操作即类名的前面定义::
:
int Node::getInfo()
{
// ... body ...
}
并且,在您的main
函数中,您需要在使用类的成员函数之前创建类的对象。
例如:
int main()
{
Node node;
node.getInfo();
return 0;
}
最好在编写代码之前修改OOP概念及其在C ++中的实现方式。 自由函数和成员函数是不同的东西。 读一本合适的书(或教程等)将帮助您为编写OOP代码奠定基础。 祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.