从头文件中调用方法

Method Calling from header files

我有一个编程任务,我应该编写用于插入和删除链表的代码。但是我已经有一段时间没有使用 C++ 了,并且很难记住某些事情。

现在,我只是想将原型方法放在头文件中,在我的 cpp 文件中定义它,然后在我的 main 方法中调用它。这就是我的。

LinkedList.h

#include <iostream>

using namespace std;

class LinkedList {

public:
    void testPrint();
};

LinkedList.cpp

#include "LinkedList.h"

int main() {
    LinkedList::testPrint();

}

void LinkedList::testPrint() {
     cout << "Test" << endl;
}

我收到以下错误

a nonstatic member reference must be relative to a specific object
'LinkedList::testPrint': non-standard syntax; use & to create a pointer to member

LinkedList::testPrint() 是一个成员函数。

它没有声明 static,这意味着它必须在特定对象上调用,例如定义为 LinkedList linked_list。然后使用 linked_list.testPrint().

选项 1 - static成员函数声明

#include <iostream>

using namespace std;

class LinkedList {

public:
    static void testPrint();
};

int main() {
    LinkedList::testPrint();
}

void LinkedList::testPrint() {
    cout << "Test" << endl;
}

选项 2 - 调用成员函数的实例化对象

#include <iostream>

using namespace std;

class LinkedList {

public:
    void testPrint();
};

int main() {
    LinkedList linked_list;
    linked_list.testPrint();
}

void LinkedList::testPrint() {
    cout << "Test" << endl;
}