允许将一个类转换为bool? [英] Allowing a class to be converted to bool?
问题描述
是否可以允许将一个类转换为bool?
例如,如果我有:
class foo {
私人:
未签名我;
};
我想评估:
if(foo)
通过查看foo.i,我该怎么做?
谢谢
Joseph
Joseph Turian写道:是否可以允许课程转换为bool?
例如,如果我有:
class foo {
私人:
未签名我;
};
<我要评估:
if(foo)
通过查看foo.i,我该怎么做?
使用转换操作符...
class foo
{
public:
operator bool ()
{
返回i!= 0;
}
..... >
Joseph Turian写道:是否可以允许将一个类转换为bool?
例如,如果我有:
class foo {
private:
未签名我;
};
我想评估:
if(foo)
通过查看foo.i,我该怎么做?
class foo
{
public:
operator bool()const
{
返回i!= 0;
}
私人:
未签名i;
};
但是要知道这可以让你的班级被转换:
foo f;
if(f); //酷
int a = f; // ..也有效
Jonathan
Jonathan Mcdougall写道:
但是要知道这可以让你的班级被转换:
foo f;
if(f); //酷
int a = f; // ..也有效
好的等等。
我创造了一个类''foo''的全部原因包装POD类型
''unsigned''是因为我想通过创建几个$ f $ b子类型的foo来确保类型安全。
>
即我希望有三个A,B和C类基本上是
类型''unsigned''。
但是,我想要A ,B和C被认为是不同的类型,并且比如说,B和B类型之间的A和B类型之间的比较导致编译器错误。
所以,这样做,我希望A,B和C继承自foo。
问题1:A,B和C是否继承自foo实现了
在A,B,
和C之间禁止比较和演员的期望效果?
问题2:添加操作员bool转换功能是否打开了我
$ b任何类型转换风险$ b?
谢谢!
Joseph
Is it possible to allow a class to be converted to bool?
For example, if I have:
class foo {
private:
unsigned i;
};
and I want to evaluate:
if (foo)
by looking at foo.i, how can I do that?
Thanks
Joseph
解决方案Joseph Turian wrote:Is it possible to allow a class to be converted to bool?
For example, if I have:
class foo {
private:
unsigned i;
};
and I want to evaluate:
if (foo)
by looking at foo.i, how can I do that?
Use a conversion operator ...
class foo
{
public:
operator bool()
{
return i != 0;
}
.....
Joseph Turian wrote:Is it possible to allow a class to be converted to bool?
For example, if I have:
class foo {
private:
unsigned i;
};
and I want to evaluate:
if (foo)
by looking at foo.i, how can I do that?
class foo
{
public:
operator bool() const
{
return i != 0;
}
private:
unsigned i;
};
But know that this makes it possible for your class to be converted:
foo f;
if (f) ; // cool
int a = f; // .. also works
Jonathan
Jonathan Mcdougall wrote:
But know that this makes it possible for your class to be converted:
foo f;
if (f) ; // cool
int a = f; // .. also works
Okay wait.
The whole reason I created a class ''foo'' which wraps the POD type
''unsigned'' is because I want to ensure type-safety by creating several
sub-types of foo.
i.e. I want to have three classes A, B, and C which are essentially of
type ''unsigned''.
However, I want A, B, and C to be considered distinct types and to
have, say, comparisons between A and B types to cause a compiler error.
So, to do so, I want to have A, B, and C inherit from foo.
Question 1: Does having A, B, and C inherit from foo achieve the
desired effect of disallowing comparisons and casts between types A, B,
and C?
Question 2: Does adding the operator bool conversion function open me
to any type-conversion risks?
Thanks!
Joseph
这篇关于允许将一个类转换为bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!