简体   繁体   中英

Method Calling from header files

I have a programming assignment where I'm supposed to write up the code for inserting and removing linked lists. However I haven't used C++ in a while and am struggling remember certain things.

Right now, I am simply trying to put a prototype method in a header file, define it in my cpp file, and then call it in my main method. this is what I have.

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;
}

I am getting the following errors

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() is a member function.

It is not declared static , so that means it must be called on a particular object, defined as LinkedList linked_list , for example. Then use linked_list.testPrint() .

Option 1 - static member function declaration

#include <iostream>

using namespace std;

class LinkedList {

public:
    static void testPrint();
};

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

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

Option 2 - Instantiated object with call to member function

#include <iostream>

using namespace std;

class LinkedList {

public:
    void testPrint();
};

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM