[英]Why can't I have a method with the same name as a member type?
Here is some code that fails in VS2012: 这是一些在VS2012中失败的代码:
class A;
class B
{
bool A();
A member; // Error: function B::A is not a type name
};
Why doesn't this work? 为什么不起作用? Obviously I'm trying to create a member of type
A
, not of type B:A()
(which isn't a type, as the compiler correctly points out). 显然,我正在尝试创建类型
A
的成员,而不是类型B:A()
(这不是类型,正如编译器正确指出的那样)。 Is there some way around this without changing the names of either B:A()
or class A
? 是否可以解决此问题而不更改
B:A()
或class A
? Can I explicitly tell the compiler that I want member
to be of type class A
? 我可以明确地告诉编译器我希望
member
为class A
类型吗?
It's possible, you just need to make clear that you want to use the class A
: 有可能,您只需要明确说明要使用
A
类 :
class A;
class B
{
bool A();
class A member;
};
It fails because they share a namespace. 它失败,因为它们共享一个名称空间。 C++ cannot, in general distinguish types and functions based on context (is
A()
a constructor or a function call). 通常,C ++不能基于上下文区分类型和函数(
A()
是构造函数还是函数调用)。 You can make it explicit which one you refer to, eg 您可以明确指出您指的是哪个,例如
class A;
class B
{
bool A();
::A member;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.