简体   繁体   中英

"identifier is undefined" when calling functions defined in class (separate cpp file) from main

I'm very new to c++ and to my understanding if i include the header file which is where the functions are defined, i should be able to call the functions from main? I have tried to add static or public before the functions but nothing seemed to change.

//heres my main

#include "pch.h"
#include "myfile1.h"
#include <iostream>

using namespace std;

int main(void){
    function1();
    function2();
}

//my myfile1 header

#ifndef myfile1_h  
#define myfile1_h

#include <iostream>

using namespace std;

class myClass{
    void function1();

    void function2();
};

#endif


//my myfile1.ccp

#include "myfile1.h"
#include <iostream>

using namespace std;

class myClass{
    void function1() {

    }

    void function2() {
    }
}

Your functions are in the myClass in myfile1. You must create object from this class, and you can use functions where in the this class. My English skills are not good but you must do this:

int main(void){
    myClass myClassObject;
    myClassObject.function1();
    myClassObject.function2();
}

If you dont want create object from this class, you can do that :

myfile1.h:

#ifndef myfile1_h  
#define myfile1_h

#include <iostream>

using namespace std;

void function1();
void function2();

#endif

myfile1.cpp:

#include "myfile1.h"

void function1(){
    cout<<"function1"<<endl;
}

void function2(){
    cout<<"function2"<<endl;
}

and main:

#include "myfile1.cpp"

int main(){
    function1();
    function2();


    return 0;
}

If you want this functions with class, you can do it for good case: myfile1.h

#ifndef myfile1_h  
#define myfile1_h

#include <iostream>

using namespace std;

class myClass{
    public: // If you want access these functions, you must use public tag.
            // If you dont use any tag, it will be private, because default tag is private.
    void function1();
    void function2();
};


#endif

myfile1.cpp

#include "myfile1.h"

void myClass::function1(){
    cout<<"function1";
}

void myClass::function2(){
    cout<<"function2";
}

main:

#include "myfile1.h"

int main(){
    myClass myClassObject;
    myClassObject.function1();
    myClassObject.function2();
    
    return 0;
}

What is your compiler or editor? If you compile that codes from terminal, you must compile it like this: g++ main.cpp myfile1.cpp

My English skills are not good. But I tried to explain.

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