Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c++ - How to get base object's data in a new derived object?

(Beginner in OOP.) I have a person class which stores the name of the person. In a derived class instance printer, I need that name so that I can do further tasks with it.

#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() {
    Person one;
    one.name = "john";
    Printer printer;
    printer.print();
    return 0;
}

What am I not doing to have printer see the data in one ? I'd be having several printer-like objects so storing "john" only once is the goal here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. You use void for main but with c++ you can only use int for it.

  2. 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).

  3. 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...