From 0db19a2570b5409f9fef24d203098a64d79809e0 Mon Sep 17 00:00:00 2001 From: JYJSXX Date: Sun, 1 Sep 2024 20:49:42 +0800 Subject: [PATCH] 1 --- include/Human.hpp | 2 +- include/Student.hpp | 3 ++- src/Human.cpp | 10 +++++++--- src/Student.cpp | 12 +++++++++--- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/include/Human.hpp b/include/Human.hpp index 2231bdf..2a307bd 100644 --- a/include/Human.hpp +++ b/include/Human.hpp @@ -9,6 +9,6 @@ private: public: explicit Human(int age, const std::string name = "") : name_(name), age_(age) {}; virtual ~Human(); - virtual char* print() const; + virtual std::string print() const; }; diff --git a/include/Student.hpp b/include/Student.hpp index 05ac91e..c461ff1 100644 --- a/include/Student.hpp +++ b/include/Student.hpp @@ -1,6 +1,7 @@ #pragma once #include "Human.hpp" +#include class Student : public Human { @@ -11,5 +12,5 @@ public: Student() = delete; explicit Student(int age, const std::string name = "", const std::string school = "") : Human(age, name), school_(school) {}; virtual ~Student() override; - virtual char* print() const override; + virtual std::string print() const override; }; \ No newline at end of file diff --git a/src/Human.cpp b/src/Human.cpp index 7e03ad3..bc1b993 100644 --- a/src/Human.cpp +++ b/src/Human.cpp @@ -1,11 +1,15 @@ #include "Human.hpp" +#include +#include Human::~Human() { printf("Human destructor called\n"); } -char* Human::print() const { - char* res = new char[100]; - sprintf(res, "My name is %s and I am %d years old\n", name_.c_str(), age_); +std::string Human::print() const { + std::string res; + std::stringstream ss; + ss << "My name is " << name_ << " and I am " << age_ << " years old\n"; + ss >> res; return res; } \ No newline at end of file diff --git a/src/Student.cpp b/src/Student.cpp index df0eedc..c7576ea 100644 --- a/src/Student.cpp +++ b/src/Student.cpp @@ -1,12 +1,18 @@ #include "Student.hpp" +#include "Human.hpp" #include "cstring" +#include +#include Student::~Student() { printf("Student destructor called\n"); } -char* Student::print() const { - char *res = Human::print(); - sprintf(res + strlen(res), "I'm from %s\n", school_.c_str()); +std::string Student::print() const { + std::string res; + std::stringstream ss; + ss << Human::print(); + ss << "I'm from " << school_ << "\n"; + ss >> res; return res; } \ No newline at end of file -- GitLab