简体   繁体   English

在 C++ 中创建新的 object 时,将未命名的 object 作为参数传递

[英]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.我想在构造函数中使用未命名的 object 作为参数,但它会产生以下错误。

I guess object name 'b2' is interpreted as function prototype or something.我猜 object 名称 'b2' 被解释为 function 原型或其他东西。

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 . b2实际上被编译器解释为一个名为b2的 function 的声明,它接受一个 function 指针,该指针返回一个AAA作为参数,并返回一个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.因为BBB没有赋值运算符,它采用 function 等。

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.这是因为BBB需要参考实际的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:要解决此问题,由于您实际上并未更改传递的AAA object,因此我建议您将BBB的构造函数更改为:

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

After all, BBB::a is just a copy of the parameter passed in BBB 's contructor.毕竟, BBB::a只是BBB的构造函数中传递的参数的副本。 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!有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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