String object in C ++

I read a book in C ++ when I came across the following example:

#include <iostream>
#include <string>

using namespace std;

int main () {
 const char *message = "how do you do\n";

 string s(message); 
 cout << s << " and its size:" << s.size() << endl;
}

I wanted to know what exactly he was doing. How can we pass the variable inte to another variable, as is done in s (message)? thanks in advance

+5
source share
7 answers

s(message)actually calls the constructor std::string, which builds a new object of this type from the specified array of characters that it points to message. sis just a conditional name assigned to a string object. std::stringis an idiomatic C ++ object for working with strings; it is usually preferred over raw C strings.

Consider this simple example:

// Declare a fresh class
class A {

   public:

      // a (default) constructor that takes no parameters and sets storedValue to 0.
      A() {storedValue=0;}

      // and a constructor taking an integer
      A(int someValue) {storedValue=someValue;}

   // and a public integer member
   public:
      int storedValue;
};

// now create instances of this class:
A a(5);

// or
A a = A(5);

// or even
A a = 5;

// in all cases, the constructor A::A(int) is called.
// in all three cases, a.storedValue would be 5

// now, the default constructor (with no arguments) is called, thus
// a.storedValue is 0.
A a;

// same here
A a = A();

std::string , , const char* - , string::string(const char*) .

+4

'' " ...", .

string s;    
s =  "how do you do\n"

( "ctor" ), .

ctor , .

int count=10;
int count(10);
+1

std::string.

++ .

std::string s = "Hello"; // implicit constructor using const char *
std::string s = std::string("Hello"); // invoke the const char* constructor of std::string
std::string s("Hello"); // another way to do the stuff above

, , std::string.

+1

:

string s(message);

, ++. , :

int i(5);
+1

const char* . .

+1
string s(message);

s string. (message), , s.

std::string ,

string(const char* s);

, s.

+1

string - , , . , , +

string a="my name is ";
string b="frustrated coder";
string c= a+b;//c="my name is frustrated coder"
cout<<c;

,

How can we pass the inte variable to another variable, as is done in c (message)?

Answer: using the assignment operator '=' for example,

string a="frustrated coder";
string b, c, d;//create strings b, c, and d
b=c=d=a;//basic usage of variables

here the variable a is assigned d, c and b. I don’t know if this is really what you want. :)

+1
source

All Articles