C ++ - 构造函数重载 - 私有和公共 [英] C++ - Constructor overloading - private and public

查看:161
本文介绍了C ++ - 构造函数重载 - 私有和公共的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能告诉我为什么以下代码会给我以下错误 - 调用重载的C(int)是不明确的



我认为由于C(char x)是私有的,只有C(float)ctor从外部是可见的,并且应该通过将int转换为float来调用。



但事实并非如此。

  class C 
{
C(char x)
{
}
public:
C(float t)
{
}
};

int main()
{
C p(0);
}


解决方案

C ++作者:Scott Meyer。这个模糊的原因是他们想要确保只改变成员的可见性不会改变其他地方已经存在的代码的含义。



否则,假设你的C类在某个地方的标题。如果你有一个私人C(int)成员,你提出的代码将调用C(float)。如果因为某些原因,C(int)成员被公开,旧代码会突然调用该成员,即使旧代码或它调用的函数都没有改变。



编辑:更多原因:



更糟糕的是,假设您有以下两个函数:

  CA :: foo()
{
return C(1.0);
}

C B :: bar()
{
return C(1.0);
}

这两个函数可以根据是否声明foo或bar作为C的朋友,或者A或B是否从它继承。具有相同的代码调用不同的函数是可怕的。



(这可能不像Scott Meyer的讨论那么好, / p>

Can you tell me why the following code is giving me the following error - call of overloaded "C(int)" is ambiguous

I would think that since C(char x) is private, only the C(float) ctor is visible from outside and that should be called by converting int to float.

But that's not the case.

class C
{
    C(char  x)
    {
    }
public:
    C(float t)
    {
    }
};

int main()
{
    C p(0);
}

解决方案

This is discussed in "Effective C++" by Scott Meyer. The reason this is ambiguous is that they wanted to ensure that merely changing the visibility of a member wouldn't change the meaning of already-existing code elsewhere.

Otherwise, suppose your C class was in a header somewhere. If you had a private C(int) member, the code you present would call C(float). If, for some reason, the C(int) member was made public, the old code would suddenly call that member, even though neither the old code, nor the function it called had changed.

EDIT: More reasons:

Even worse, suppose you had the following 2 functions:

C A::foo() 
{
    return C(1.0);
}

C B::bar() 
{
    return C(1.0);
}

These two functions could call different functions depending on whether either foo or bar was declared as a friend of C, or whether A or B inherits from it. Having identical code call different functions is scary.

(That's probably not as well put as Scott Meyer's discussion, but that's the idea.)

这篇关于C ++ - 构造函数重载 - 私有和公共的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆