我在 Quora 上的 C++
代码中看到了匿名类。它已成功编译并运行。
代码在这里:
#include <iostream>
auto func()
{
class // no name
{
public:
int val;
} a;
a.val = 5;
return a;
}
int main()
{
std::cout << func().val << std::endl;
return 0;
}
那么,它在 C++ 中有效吗?
另外,我很想知道,是否可以在 C++ 中使用匿名类?
最佳答案
不仅如此,您还可以使用 decltype
创建更多的类实例。
#include <iostream>
class
{
public:
int val;
} a;
int main()
{
decltype(a) b;
a.val = 10;
b.val = 20;
std::cout << a.val << std::endl;
std::cout << b.val << std::endl;
return 0;
}
输出:
10
20
关于c++ - 是否可以在 C++ 中使用匿名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44173737/