简体   繁体   English

为什么我不能拥有某些私有成员函数?

[英]Why can't I have certain private member functions?

Given a class, why can we implement certain private member functions, but not other private member functions?给定一个类,为什么我们可以实现某些私有成员函数,而不能实现其他私有成员函数? For instance, see below:例如,见下文:

header file:
class A
{
    ....
    struct B
    {
    ....
    }
    int f(); 
    B* g();
}

cpp file:
int A::f(){...} // will compile
B*  A::g(){...} // will not compile!

The error is "Unknown type name 'B'", but my actual code has some more details.错误是“未知类型名称‘B’”,但我的实际代码有更多细节。

B*  A::g(){...}

B is not visible outside A . BA之外不可见。

A::B*  A::g(){...}

This has nothing to do with private members.这与私人成员无关。 Since B is declared inside A , its not in global scope, hence you need to specify what B you are referring to.由于BA内部声明,它不在全局范围内,因此您需要指定您所指的B

Alternatively to the other answer you can use trailing return types替代其他答案,您可以使用尾随返回类型

auto A::g() -> B* {...}

Before A::g() you have to use A::B .A::g()之前,您必须使用A::B After A::g() you can simply use B .A::g()您可以简单地使用B

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

相关问题 我无法在我的操作员函数中访问我的私有数据成员和 function - I can't access my private data member and function in my operator functions 为什么不能使用与成员类型同名的方法? - Why can't I have a method with the same name as a member type? 为什么静态成员函数不能恒定? - Why can't static member functions be constant? 为什么我不能在一个属于另一个类的私有成员的类中声明一个朋友? - Why can't I declare a friend in one class that is a private member of another class? 为什么我不能从不同命名空间中的友元类更改类的私有成员? - Why can't I change a private member of a class from a friend class in a different namespace? 为什么PRIVATE成员函数不能成为另一个类的朋友函数? - Why can't a PRIVATE member function be a friend function of another class? 为什么我的朋友类不能访问私有成员? - Why can't my friend class access a private member? 为什么这个朋友的功能无法访问该类的私有成员? - Why this friend function can't access a private member of the class? 如何通过显式名称访问某些成员函数 - How can I access certain member functions through an explicit name 为什么我不能成功初始化类中的私有数据成员? - Why didn't I initialize the private data member in class successfully?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM