[英]Troubles with reference variables/pointers an class members [C++]
I've been working on a project and have quite a few classes, a few of which look like this: 我一直在做一个项目并且有很多课程,其中一些是这样的:
class A
{
// stuff;
};
class B
{
A& test;
public:
B(A& _test) :
test(_test)
{};
void doStuff();
};
class C
{
A foo;
B bar(foo);
void exp()
{
bar.doStuff();
}
};
This ends up breaking in class C when C::foo is not a type name. 当C :: foo不是类型名称时,这最终会在C类中中断。 In my bigger project, where everything is broken up into their separate .cpp and .h files, I don't see that error if I #include"Ch" in Bh, but there is still an error in C.cpp where bar is completely unrecognized by my compiler (Visual Studio 2013).
在我的大项目中,所有内容都被分解为单独的.cpp和.h文件,如果我在Bh中#include“Ch”,我没有看到错误,但是C.cpp中仍然存在错误,其中bar是我的编译器完全无法识别(Visual Studio 2013)。 There error persists even if A& is an A* instead (changing the code from references to pointers where necessary, of course).
即使A&是A *,也会出现错误(当然,在必要时更改代码引用的代码)。 Does anyone have any tips to what is going on here?
有没有人对这里发生的事情有任何提示?
This line of code: 这行代码:
B bar(foo);
Attempts to declare a member function named bar
which returns a B
and takes an argument of type foo
. 尝试声明一个名为
bar
的成员函数,它返回一个B
并接受一个类型为foo
的参数。 However, in your code, foo
is not a type - it's a variable. 但是,在你的代码中,
foo
不是一个类型 - 它是一个变量。 I'm guessing you meant to initialize bar
instead: 我猜你的意思是初始化
bar
:
B bar{foo}; // non-static data member initializers must be done with {}S
or just write out the constructor: 或者只写出构造函数:
C()
: bar(foo)
{ }
Additionally, this constructor assigns your reference test
to the temporary _test
: 此外,此构造函数将您的参考
test
分配给临时_test
:
B(A _test) :
test(_test)
{ }
You want to take _test
by reference: 您想通过引用获取
_test
:
B(A& _test) : test(_test) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.