no known conversion from'const char [4]' to'std::__cxx11::string &'(aka'basic_string<char…The problem of reference transfer

I encountered an error when testing a piece of code today:
qt error message
**The key point is this sentence "no known conversion from'const char [[4]]' to'std::__cxx11::string &'(aka'basic_string &') for 1st argument ..."

The code is as follows: **

The declaration class in the h file is as follows:

class Person 
{
    
    
public:
    Person( string &name, int age);
    virtual ~Person();
    virtual void func();

private:
    PersonImpl *mPersonImpl;
};

In the man function:

int main()
{
    
    
    Person *people = new Person("Tom", 12);
    return 0;
}

Reason for error:

It is a relatively common mistake to define the formal parameters of the function that will not change as (ordinary) references [should be const references].

Lead to [1]:

1. Misleading functions can modify the value of its actual parameters;
2. Greatly restrict the types of actual parameters that the function can accept [const objects, literal values, and objects that require type conversion can no longer be accepted]

solve:

    Person( string &name, int age);
    Person(const string &name, int age); //修改为常引用

or:

    string str("Tom");
    Person *people = new Person(str, 12);   //传string对象,而非字面量

references:

[1] https://blog.csdn.net/goldcarpenter/article/details/81975241

Guess you like

Origin blog.csdn.net/junh_tml/article/details/114990246