向类的构造函数添加虚拟参数来解决调用歧义是否违反任何规则?
采用以下类和两个对象定义:
class Rect{
public:
enum centimeter;
enum meter;
Rect(double len,double wid,enum centimeter){
length=(len/100);
width=(wid/100);
}
Rect(int len,int wid,enum meter){
length=len;
width=wid;
}
//rest of implementation
private:
double length;//in meters
double width;//in meters
};
Rect obj1(10,5,Rect::centimeter());
Rect obj2(10,5,Rect::meter());
前面的两个构造函数具有虚拟枚举参数,以解决这些虚拟参数不存在时导致的调用歧义。现在,尽管可以在这里使用命名构造函数,但如果我坚持使用这些虚拟参数,这是否违反了我应该注意的任何编码规则?
take following class and two object definitions:
class Rect{
public:
enum centimeter;
enum meter;
Rect(double len,double wid,enum centimeter){
length=(len/100);
width=(wid/100);
}
Rect(int len,int wid,enum meter){
length=len;
width=wid;
}
//rest of implementation
private:
double length;//in meters
double width;//in meters
};
Rect obj1(10,5,Rect::centimeter());
Rect obj2(10,5,Rect::meter());
two previous constructors have dummy enum parameters to solve calling ambiguity caused in case these dummy parameters didn't exist. Now in spite of possibility of using named constructors here, if I insist on using these dummy parameters, does this violate any coding rule that I should be aware of ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我觉得这违反了我的口味。我会这样编码:
I think it violates my taste. I would code it like this:
BOOST_STRONG_TYPEDEF 可能是这里的答案。
BOOST_STRONG_TYPEDEF could be the answer here.
STL 使用该习惯用法来代替概念来区分迭代器类型。
STL uses that idiom to differentiate iterator types in lieu of concepts.
不能说这违反了规则,但是......它不容易阅读。
为什么不能声明 a
并将其用作构造函数参数?或者
根据我的口味,两者都比当前代码更好。
Can't say this breaks a rule, but... It isn't easy to read.
Why can't you declare a
and use it as the constructor parameter? Or it can be
Either is better than current code at my taste.
除了其他人写的之外,这个逻辑很糟糕,因为
Rect(99,99,Rect::centimeter())
等于Rect(0,0,Rect::centimeter( ))
。如果您在内部存储米,请不要提供厘米的接口,无论是这种方式还是任何其他方式。
In addition to what others wrote, this logic is bad, because
Rect(99,99,Rect::centimeter())
is equal toRect(0,0,Rect::centimeter())
.If you are storing meters internally, do not provide an interface with centimetres, not this way nor any other way.