简体   繁体   中英

passing an unnamed object as an argument when making a new object in C++

I want to use unnamed object as an argument in constructor, but it generates the following error.

I guess object name 'b2' is interpreted as function prototype or something.

class AAA
{
private:
    int m_val;
public:
    AAA(int a) : m_val(a) {}
};

class BBB
{
private:
    AAA a;
public:
    BBB(AAA &a_) : a(a_) {}
};

int main()
{
    AAA a(5), a1(10);
    BBB b(a), b1(a1);
    b = b1;
    BBB b2(AAA());
    b = b2;
}
.\ex_unnamed.cpp: In function 'int main()':  
.\ex_unnamed.cpp:21:9: error: no match for 'operator=' (operand types are 'BBB' and 'BBB(AAA (*)())')  
     b = b2;  
         ^~  
.\ex_unnamed.cpp:8:7: note: candidate: 'constexpr BBB& BBB::operator=(const BBB&)'  
 class BBB  
       ^~~  
.\ex_unnamed.cpp:8:7: note:   no known conversion for argument 1 from 'BBB(AAA (*)())' to 'const BBB&'  
.\ex_unnamed.cpp:8:7: note: candidate: 'constexpr BBB& BBB::operator=(BBB&&)'  
.\ex_unnamed.cpp:8:7: note:   no known conversion for argument 1 from 'BBB(AAA (*)())' to 'BBB&&'  

Firstly, this does not mean what you think it means:

BBB b2( AAA() );

b2 is actually interpreted by the compiler as a declaration of a function called b2 which takes a function pointer which returns an AAA as a parameter, and which returns a BBB .

For my compiler, look at the signature:

在此处输入图像描述

So then this fails:

b = b2;

because BBB does not have an assignment operator which takes a function, etc.

You can fix this by doing this:

int main()
{
    AAA a(5), a1(10);
    BBB b(a), b1(a1);
    b = b1;
    BBB b2( AAA(5) );
    b = b2;
}

BUT it will still not compile. This is because BBB requires a reference to an actual AAA object.

To fix this, since you are not actually changing the AAA object passed, I recommend that you change the constructor of BBB to this:

BBB(const AAA& a_) : a(a_) {}

After all, BBB::a is just a copy of the parameter passed in BBB 's contructor. The final result:

class AAA
{
private:
    int m_val;
public:
    AAA(int a) : m_val(a) {}
};

class BBB
{
private:
    AAA a;
public:
    BBB(const AAA& a_) : a(a_) {}
};

int main()
{
    AAA a(5), a1(10);
    BBB b(a), b1(a1);
    b = b1;
    BBB b2( AAA(5) );
    b = b2;
}

It works!

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