when to use '+'

i try to use the following code but failed (compilation error occurred)
1
2
3
string toString(){
   return _name + " is " + age;
}

and
 
   cout << _name + " !" << endl;

In Java, I think my usage is ok. can anyone explain to me when should I use "+" in c++?
many thanks.
It depends on wether the previous operation returns a string or not.

In your second case, "cout << _name" returns a stream so that you can chain the calls to <<, and streams don't support the + operator.
If you need only to output the result string you can write simply

cout << _name << " is " << age;
If you need the string itself you can write

1
2
3
4
string toString()
{
   return ( _name + " is " + to_string( age ) );
}


provided that _name has type std::string

toString() is java thinking. C++ has overloading:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class myClass
{
public:
  string name;
  int age;

  friend ostream& operator<<(ostream& out, myClass& data)
  {
    return out << "My name is " << name << " and I am " << age << endl;
  }
};


// Which allows this:

cout << instanceOfMyClass;


Other way is to use std::ostringstream. For example


1
2
3
4
5
6
7
8
std::string toString()
{
   std::ostringstream os;

   os << _name << " is " << age;

   return ( os.str() );
}
It should work as-is to an extent. See if you can compile the example here:
http://cplusplus.com/reference/string/operator+/

Edit:
I see the problem! If _name is a const char* type instead of a std::string type, then you are invoking this function:
const char* operator+ (const char* lhs, const char* rhs);
That function doesn't exist and you can't make it because you can't redefine operator functions with only basic types.

Second, if age is an integer, then you are invoking
const char* operator+(const char* lhs, const int rhs)
which also doesn't exist and can't be created because it only uses basic types.

C++ is much lower-level than Java. You are closer to the processor and so a lot of this automatic type stuff doesn't exist. In C++ we know exactly what every bit does at every moment instead of relying on high-level magic to do things for us. This lets us write code that is more specific to what we need and prevents us from accidently calling functions that will add overhead to our project. It may be more difficult to write at times, but the trade-off is that it will usually be faster (fewer instructions). There is also less "guessing" when we want to know exactly what is happening.
Last edited on
Topic archived. No new replies allowed.