简体   繁体   中英

How to Return struct in a class when gthe struct is declared outside the class?

I am trying to get the structure of strings "Johna" "Smith" to return by calling a class. I am very new and confused on OOP and pointers and I wanted to know if Im on the right track and what I can do to get rid of the following errors:

  1. "cannot convert 'name' to 'const char*'" on line 46... This line
printf(s1.get_name())

Any help is appreciated, here is the full code

#include <stdio.h>

#include <algorithm>  // for std::find
#include <cctype>
#include <ctime>
#include <iostream>
#include <iterator>  // for std::begin, std::end
#include <vector>

using namespace std;

enum year { FRESHMAN, SOPHOMORE, JUNIOR, SENIOR };
struct name {
    string firstName;
    string lastName;
};
class Student : name {
   private:
    name Name;

   public:
    void setname(string fn, string ln) {
        Name.firstName = fn;
        Name.lastName = ln;
    }
    name get_name() { return Name; }
};

int main() {
    Student s1;
    s1.setname("johna", "smith");
    printf(s1.get_name()) return 0;
}

Your code is totally fine, you're just confused about the printf function of C++.
Maybe you have experience with python, javascript, or other scripting languages that the print function accepts anything and prints it out nicely. That is not the case with a strong typed language like C++.

You should read the docs on printf .

name s1_name = s1.get_name();
printf("%s %s\n", s1_name.firstName.c_str(), s1_name.lastName.c_str());

Alternatively, you could use std::cout , which will handle the format type for you.

std::cout << s1_name.firstName << ' ' << s1_name.lastName  << '\n';

You could also define a way to let std::cout know how to handle your struct:


struct name
{
    string firstName;
    string lastName;
    friend std::ostream& operator <<(ostream& os, const name& input)
    {
        os << input.firstName << ' ' << input.lastName << '\n';
        return os;
    }
};
...
std::cout << s1_name;

To add to what thedemons posted, when you do not provide format specifiers as the first argument to printf, it opens room for a potential format string vulnerability. Because you did not specify what format the first parameter is, if the user of the program was able to change the contents of Name to %x %x %x %x, the user would be able to read memory off of the stack and leak information which can lead to a plethora of issues. Make sure to always use format specifiers such as %s or %d to avoid these issues when using printf:)

better is to use cout in c++

printf(s1.get_name())

should be

cout << s1.get_name();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM