OneBytePerHour
OneBytePerHour

Reputation: 25

Return variable as a Class Object

I have created a string class using a character array.

I actually to need place that array instead of class object. here's an easy example.

I want to print A as an integer , not B as a class object which isn't possible.

#include <iostream>

class T 
{
   int A ;

   public : T ( )
   {
       A = 10 ;
   }
} ;

void main ( )
{
    T B ;
    std :: cout << B ;
}
  1. Is it possible?

  2. Okay, but how?

Upvotes: 0

Views: 116

Answers (2)

iluvthee07
iluvthee07

Reputation: 501

One method is to add a function to the public part of your class definition that returns the value of A:

class T{
...
public:
...
int retA(){
    return A;
}
};

int main{
T B;
cout << B.retA();
return 0;   //This is what chris said in his comment!
}

Hope this helps!

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227370

You need an output stream operator:

std::ostream& operator <<(std::ostream& o, const T& t)
{
  return o << t.A;
}

Note that, since A is private, it would have to be a friend of T.

Upvotes: 4

Related Questions