How to print a variable from main using a function in a class, Help understand OOP C ++

Section 9 (1/4) of 11 of my C ++ Implementation Web Cluster;

I have no idea what I am doing. I'm not even sure what the search terms are (first touch with OOP).

- I need to print cin in main with a function in a class, So far I have come up with a class with a string variable and a function that does nothing,

#include <iostream>
#include <string>
using namespace std;
        class printclass 
    {
        public:        
        string array;
        void print(); 
    };

    void printclass::print()
    {
        cout << array;
    }

      

Main program (cannot be edited);

   int main()
{
  char array[50];

  cout << "Enter string:";
  cin.get(array, 50);

  printclass printer;
  printer.print(array);
}

      

I understand that I printclass printer;

create a "printer" object with printclass and therefore knows how to use functions in the class on some empty page declared with a call, am I far away?

How to print the value of an array in main using a function?

The exercise has been translated from Finnish, please excuse the stupid grammar and the stupidity of the user. Thank you for your time!

+3


source to share


1 answer


I'm far away?

Curious. You misused your interface printclass

. Here's the correct example 1 from the above example:

class printclass {
public:
    printclass();
    void print(const char* str);
};

      

From this it is easy to see your mistake; you assumed that your class needs to store an array for printing and the interface passes it directly. This is enough to be implemented print

in terms str

without any member variables:



void printclass::print(const char* str) { // could be const
    std::cout << str;
}

      

Note: the constructor can of course be left alone and will default to whatever you want.


1 One of many possible interfaces, but I chose the most likely one.

+1


source







All Articles