You have made the member vars public
but this is not the right approach for the OOP
, the right one is to have them under private access specifier and use setters and getters.
Now to your mistakes:
You use void
for main
but with c++ you can only use int
for it.
You use std::string
as an argument for printf
but it can't accept it. (I passed the c_string
of the std::string
to correct that).
You use an object, from the parent class, and give it a name then use another object, from the driven one, to print the name of the first one. (I used only one)
#include <iostream>
#include <string>
class Person{
public:
std::string name;
};
class Printer: public Person{
public:
void print(){
printf("%s",this-> name.c_str());
}
};
int main() {
Printer printer;
printer.name = "name";
printer.print();
}
After your comments, I have updated Printer
class to do your inttent
#include <iostream>
#include <string>
class Person{
public:
std::string name;
};
class Printer{
public:
void print(const Person& person ){
printf("%s", person.name.c_str());
}
};
int main() {
Person one;
one.name = "name";
Printer printer;
printer.print(one);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…