gpt4 book ai didi

c++ - 私有(private)联盟的 setter/getter - C++

转载 作者:行者123 更新时间:2023-11-28 02:40:26 26 4
gpt4 key购买 nike

我有一个带有私有(private) union 的类 Foo:

class Foo
{
public:
static Foo foo(int type);
static Foo foo(double type);
static Foo foo(bool type);
static Bar getBar(Foo foo);
private:
union Bar
{
int iBar;
double rBar;
bool bBar;
} bar;
};

我可以编写一个返回适当 Bar 的通用 getter 吗?

我试过:

Bar Foo::getBar(Foo foo) 
{
return foo.bar;
}

还有其他变体,但编译器无法识别“Foo”中名为“Bar”的类型。

最佳答案

有两点 - 与数据和函数成员不同,成员类型需要在使用前声明,并且您需要在类外定义中完全限定嵌套类型:

class Foo {
// here, compiler doesn't yet know what Bar is
union Bar {
int iBar;
double rBar;
bool bBar;
} bar; // now it does
public:
static Bar getBar(Foo); // so use it
};

Foo::Bar Foo::getBar(Foo foo) { return foo.bar; }
// ^^^^^

如果要有任何实际用途,您可能还想将 Bar public 设为public。希望对您有所帮助。

关于c++ - 私有(private)联盟的 setter/getter - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com