I am trying to learn how to us functions in seperate files but i fail each time i try.
I have some problems with Calling (a) function(s) from a class that is in a seperate file.
Example
file: main.cpp
#include <iostream>
#include "myClass.h"
using namespace std;
myClass::myClass()
{
public:
myClass(){
cout << "this is the constructor\n\n";
}
void setName(string x){
name = x;
}
string getName(){
return name;
}
private:
string name;
};
Could some1 please help me, i don't know how to do this right and can't find a explanation on the internet how to do this.
Maybe a example how to call a simple function from a class in a seperate file(with .cpp &.h)
int main()
{
myClass mc;
mc.setName("Santa");
cout << mc.getName() << endl; // making the output a bit nicer
return 0;
}
myClass.h contains the class definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#pragma once
#include<iostream>
#include<string>
using std::string;
class myClass
{
public:
string name;// member variables go here
void setName(string x);
string getName();
myClass(void);
~myClass(void);
};
myClass.cpp contains the function definitions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "myClass.h"
myClass::myClass(void){
std::cout << "this is the constructor\n\n";
}
myClass::~myClass(void){
std::cout << "this is the destructor\n\n";
}
void myClass::setName(string x){
name = x;
}
string myClass::getName(){
return name;
}
#include "myClass.h"
#include <iostream>
usingnamespace std;
myClass::myClass() //remove this
{ //and this
public: //use public keyword only in declaration (MyClass.h)
myClass(){
cout << "this is the constructor\n\n";
}
void MyClass::setName(string x) { //use full name and :: operator
name = x;
}
string MyClass::getName(){ //use full name and :: operator
return name;
}
private: //use private keyword only in declaration (MyClass.h)
string name; //this shall be only in declaration (MyClass.h)
}; //remove this too