In C++, i have:
//Base1.h
#ifndef BASE1_H
#define BASE1_H
#include <iostream>
#include <string>
#include "Base2.h"
using namespace std;
class Base1{
private:
string name;
public:
Base1(string _name);
void printSomething();
string getName();
};
#endif
In Base1.cpp i implement constructor Base1(string _name) and string getName() as normal, and the printSomething():
void Base1::printSomething(){
Base2 b2;
// how to pass a parameter in the following code?
b2.printBase1();
}
// This is Base2.h
#ifndef BASE2_H
#define BASE2_H
#include <iostream>
#include <string>
#include "Base1.h"
using namespace std;
class Base2{
public:
Base2();
void printBase1(Base1 b);
};
#endif
And Base2() constructor i implement as usual, this is my printBase1(Base1 b):
void Base2::printBase1(Base1 b){
cout << b.getName();
}
So, in the end, i want to use printSomething() in Base1 class, but i don’t know how to pass parameter to the b2.printBase1() in printSomething() as above in my code. is there anything like b2.printBase1(this) in C++? If not, can you give me a suggestion?
Since
thisis a pointer in C++, you need to dereference it:Note that you have circular includes, you should remove
#include "Base2.h"fromBase1.h. Also look into passing parameters by (const) reference, especially for non-POD types, otherwise you might not get the expected behavior.For example, your signature is
when you call it, you create a copy of the parameter in the function, and thus operating on a copy. You should change this to:
or
Pass by value only when you’re certain you need a copy.