Why can I use auto on a private type?(为什么我可以在私有类型上使用 auto ?)
问题描述
以下代码编译并运行(vc2012 & gcc4.7.2)让我有些惊讶
I was somehow surprised that the following code compiles and runs (vc2012 & gcc4.7.2)
class Foo {
struct Bar { int i; };
public:
Bar Baz() { return Bar(); }
};
int main() {
Foo f;
// Foo::Bar b = f.Baz(); // error
auto b = f.Baz(); // ok
std::cout << b.i;
}
这段代码编译是否正确?为什么它是正确的?为什么我可以在私有类型上使用 auto,而我不能使用它的名称(如预期的那样)?
Is it correct that this code compiles fine? And why is it correct? Why can I use auto on a private type, while I can't use its name (as expected)?
推荐答案
auto的规则大部分与模板类型推导相同.发布的示例的工作原理与您可以将私有类型的对象传递给模板函数的原因相同:
The rules for auto are, for the most part, the same as for template type deduction. The example posted works for the same reason you can pass objects of private types to template functions:
template <typename T>
void fun(T t) {}
int main() {
Foo f;
fun(f.Baz()); // ok
}
您问,为什么我们可以将私有类型的对象传递给模板函数?因为只有类型的名称是不可访问的.该类型本身仍然可用,这就是为什么您可以将其返回给客户端代码.
And why can we pass objects of private types to template functions, you ask? Because only the name of the type is inaccessible. The type itself is still usable, which is why you can return it to client code at all.
这篇关于为什么我可以在私有类型上使用 auto ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我可以在私有类型上使用 auto ?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
