函数未在范围内声明/如何一起使用 header.h、header.cpp 和 main.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()
不是免费函数。它是classNode
的成员函数。因此,它需要像这样在 class 名称之前使用范围解析运算符进行定义,即 ::
:
int Node::getInfo()
{
// ... body ...
}
并且,在您的 main
函数中,您需要在使用其成员函数之前创建 class 的对象。
例如:
int main()
{
Node node;
node.getInfo();
return 0;
}
最好在编写代码之前复习一下 OOP 概念及其在 C++ 中的实现方式。自由函数和成员函数是不同的东西。阅读一本合适的书(或教程等)将帮助您为编写 OOP 代码打下基础。祝你好运!
我完全是 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()
不是免费函数。它是classNode
的成员函数。因此,它需要像这样在 class 名称之前使用范围解析运算符进行定义,即 ::
:
int Node::getInfo()
{
// ... body ...
}
并且,在您的 main
函数中,您需要在使用其成员函数之前创建 class 的对象。
例如:
int main()
{
Node node;
node.getInfo();
return 0;
}
最好在编写代码之前复习一下 OOP 概念及其在 C++ 中的实现方式。自由函数和成员函数是不同的东西。阅读一本合适的书(或教程等)将帮助您为编写 OOP 代码打下基础。祝你好运!