skip to Main Content

I’m practicing <thinking in c++ > for chapter5, ex01:
Write a struct called Lib that contains three string objects a, b, and c.
In main( ) create a Lib object called x and assign to x.a, x.b, and x.c.
Print out the values.

in the beginning, I’m trying:

// ex02.cpp
#include <iostream>
#include <string>
using namespace std;

struct Lib {
    string a;
    string b;
    string c;
};

int main(){
    Lib x;
    x.a = 1;    // here I forgot the string object, and incorrectly assign the wrong value to x.a
    x.b = 2;
    x.c = 3;
    cout << x.a << " " << x.b << " " << x.c << endl;
    return 0;
}

and it can compile successfully, but the run result seems only two blank spaces:

[root@VM-0-2-centos ch05]# g++ ex02.cpp 
[root@VM-0-2-centos ch05]# ./a.out 
  
[root@VM-0-2-centos ch05]# 

at this time I find the wrong assignment. but why it should not give a compile error?
when I modify the assignment to the follows:

    x.a = "hello";     
    x.b = "world";
    x.c = "welcome";

it compiles success, and give the right run result:

[root@VM-0-2-centos ch05]# g++ ex02.cpp 
[root@VM-0-2-centos ch05]# ./a.out 
hello world welcome
[root@VM-0-2-centos ch05]# 

my question is why x.a = 1 can compile success?
and when I try:

string test = 1;

it will compile error:

error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]

2

Answers


  1. Chosen as BEST ANSWER

    Thx, @Muqali He, you give me the hint and direction. I try to understand the string class from here: https://www.cplusplus.com/reference/string/string/operator=/ And I understand a bit more. for c++98, when I use "=", there is three overload member function:

    enter image description here

    when I try:

    string t2;
    t2 = "test";
    

    it's OK. and I try:

    string t3;
    t3 = 256;
    

    it will get a warning:

    warning: overflow in implicit constant conversion
    

    at this time, 256 will be recognized as a char. when you output this value, it will transform into its ASCII code:

    string t4;
    t4 = 100;
    cout << "t4= " << t4 << endl;
    

    the ouput is

    t4 = d
    

    if I try:

    string t5 = 100;    // it will compile error
    

    because there's no corresponding constructor enter image description here


  2. U need to verify my statement by yourself. To see string code.
    First, When u declare Lib x, the member of x (a, b, c) will call string constructor. So when assign value to the member of x (x.a = 1), it will call "=operation".

    However, string test = 1, it will call constructor.

    the most difference is caller. the type of parameter of string constructor is "const char*", but "=operation" can get other type of parameter. So, x.a = 1 at compile is passing.
    Note, "int" will cast to a certain type by default.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search