简体   繁体   中英

C++ error: no matching function for call to

Here's the error I got : "no matching function for call to 'MemberForTest::MemberForTest'..."

Here is the code:

#include "Base.h"
#include "Date.h"

class MemberForTest: public tp::Base
{
public:
    MemberForTest(std::string& name, std::string& firstname,
            Date& birthday, std::string& telephone);

};




class Member
{
public:
    Member() :
        perso("Hall", "roger", (12,12,1990), "(999) 444-4545")
    {
    };

    MemberForTest perso;
};

Base is an abstract class. My teacher used the same approach to get to the base class constructor and he does not need to create a function (MemberForTest::MemberForTest). Even if I create the function, the error is still there. Can you help me?

Also, I probably have to pass an object date (Date date(12,12,1990)) rather than (12,12,1990) as parameters. How can I do that?

The expression that you use to initialize Date , namely

(12,12,1990)

is a comma expression that evaluates to an int (specifically, 1990 , the last number in the chain of comma-separated numbers). The error indicates that an int is incompatible with a Date .

Modify your code to construct a Date object instead. Unfortunately, you cannot do it inline, because MemberForTest constructor takes the Date parameter by non-constant reference. If you change the constructor to take parameters by constant reference, like this

MemberForTest(const std::string& name, const std::string& firstname,
        const Date& birthday, const std::string& telephone);

you should be able to do this:

Member() :
    perso("Hall", "roger", Date(12,12,1990), "(999) 444-4545")
{
};

When a parameter is declared as a reference to non-const, such as std::string& name , its argument needs to be an lvalue (a named object). You're passing string literals - these are arrays of characters, not std::string , and need to be converted. The result of a conversion is a temporary object, an rvalue. The language rule says that these cannot be passed to a reference to non-const.

You need to either declare the constructor to take const std::string& (since you won't be changing the arguments), or create an object of std::string type first:

void foo(std::string& s);
std::string str;
foo(str);

Also, (12,12,1990) does not create a temporary Date object (for that you'd need to use functional style cast - Date(12,12,1990) ). It's a parenthesized expression, using the comma operator , that evaluates the left hand operands, discards them, and return the rightmost operand (integer literal 1990 ).

And the same applies as with string parameters, you need to take const Date& .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM