Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何处理对类型';A';无法绑定到不相关类型的值';B';对于这个指针?_C++ - Fatal编程技术网

C++ 如何处理对类型';A';无法绑定到不相关类型的值';B';对于这个指针?

C++ 如何处理对类型';A';无法绑定到不相关类型的值';B';对于这个指针?,c++,C++,目前我遇到了第22条军规的情况。我有以下代码 #include <iostream> class B; class A{ public: A(B& _b):b(_b){} private: B& b; }; class B{ public: B(int _x):x(_x),a(*this){} private: A& a; int x; }; int main(){ B b(1); } 这再次

目前我遇到了第22条军规的情况。我有以下代码

#include <iostream>
class B;

class A{
public:
    A(B& _b):b(_b){}

private:
    B& b;
};


class B{

public:
    B(int _x):x(_x),a(*this){}

private:
    A& a;
    int x;

};

int main(){

  B b(1);

}

这再次给出了一个错误,即
字段的类型“B”不完整。
(我以前只在“xxx.h”未包含时看到此错误,因为编译器不知道类大小),但它们位于同一个翻译单元中。为什么编译器还在抱怨?传递
r值这个对象的问题有什么解决方法吗?或者我是否陷入了糟糕的设计中


供以后阅读:除了peppe的回答还有很好的描述

您没有构建任何对象。您正在尝试将
a
(左值引用)设置为使用
a(B&B)
构造函数构建的临时a对象

B(int)
构造函数的初始化列表中的
a(*this)
表达式中,
*this
生成一个
B&
,它不能绑定到
a&
,因为这两个类不相关

因此,尝试了隐式转换。有一种方法可以从
B&
中获取
a
:应用
a(B&)
构造函数来获取临时
a
对象。但是,现在您有了一个临时的
a
,它不能绑定到
a
,这是一个非常量左值引用。临时值只能绑定到常量左值引用或右值引用

这正是编译器告诉您的:

<source>: In constructor 'B::B(int)':
<source>:16:23: error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
     B(int _x):x(_x),a(*this){}
                       ^~~~~
<source>:6:5: note:   after user-defined conversion: A::A(B&)
     A(B& _b):b(_b){}
:在构造函数“B::B(int)”中:
:16:23:错误:从“A”类型的右值初始化“A&”类型的非常量引用无效
B(int_x):x(x),a(*this){
^~~~~
:6:5:注意:用户定义转换后:A::A(B&)
A(B&_B):B(_B){}

您的代码不包含任何右值引用。@KerrekSB不是
*此r值引用
?您想要此代码做什么(
a(*this)
)怎么办?@OliverCharlesworth我想让一个类有B的实例,这样我就可以从A调用B的方法。@vantamula-但是没有
A
-
A
是一个引用。好吧,那么你的意思是
A(*这个)
是右值,我将其分配给左值?我希望我已经解释过了。感谢您的详细回答,是的,现在它更有意义了
<source>: In constructor 'B::B(int)':
<source>:16:23: error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
     B(int _x):x(_x),a(*this){}
                       ^~~~~
<source>:6:5: note:   after user-defined conversion: A::A(B&)
     A(B& _b):b(_b){}