简体   繁体   English

为什么不能使用与成员类型同名的方法?

[英]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 ? 我可以明确地告诉编译器我希望memberclass 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.

相关问题 为什么我不能拥有指向与成员变量具有相同指针类型的对象的指针? - Why can't I have pointers to objects, which have the same type of pointer as a member variables? 为什么类不能为函数和数据成员具有相同的名称? - Why can't a class have same name for a function and a data member? 为什么我不能在同一行中定义两个与类相同类型的成员指针 - Why can't I define two member pointers that are the same type of the class in the same row 为什么我不能拥有某些私有成员函数? - Why can't I have certain private member functions? 为什么 function 名称不能与返回名称类型相同? - Why can't function name be the same as return name type? 为什么静态数据成员不能与非静态数据成员具有相同的名称? - Why can't a static data member has the same name with non-static data member? 为什么我不能将类的类型成员作为模板参数传递? - Why can't I pass a type member of a class as a template parameter? 为什么内部 class 和外部 class 不能同名? - Why can't inner class and outer class have same name? 为什么类方法不能使用相同的名称调用全局函数? - Why can't a class method call a global function with the same name? 一个类可以在同一个命名空间中有一个同名的成员吗? - Can a class have a member that is another with the same name in the same namespace?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM