【问题标题】:Constructing an object other than specified parameters NOT giving me errors构造指定参数以外的对象不给我错误
【发布时间】:2021-10-31 04:22:58
【问题描述】:

我正在阅读一本名为 Programming Principles and Practices using C++ 的书,但发现类构造的一种奇怪行为。 假设我有一个类如下:

class Foo {
public:
    Foo(int x)
        : y { x } { }

private:
    int y;
};

我还有另一个类,它有一个类 Foo 的实例作为其成员对象

class Bar {
public:
    Bar(Foo x)
        : y { x } { }

private:
    Foo y;
};

当我执行以下操作时:

int main()
{
    Bar obj_1 { Foo { 1 } };
    Bar obj_2 { 2021 }; // this doesn't give me error?

    return 0;
}

obj_1 是按照构造函数中的指定构造的,但 obj_2 没有给我任何错误消息,而且对我来说,它似乎只是 神奇地 起作用。 我将一个类的成员作为另一个类的实例的意图是强制构造函数将类实例作为其参数,而不是整数。

为什么它不给我不正确的类型错误?

【问题讨论】:

  • 魔法:编译器很聪明。它需要Foo,但它得到了int,并且知道如何将int 变成Foo

标签: c++ class constructor


【解决方案1】:

您可以通过声明Foo 构造函数explicit 来防止这种隐式转换

explicit Foo(int x) : y { x } { }

main 中,这将要求调用者将其obj_2 实例化更改为

Bar obj_2 { Foo{2021} };

【讨论】:

  • 或 Bar(int)=delete;只是为了防止 Bar 构造 int。
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2018-01-18
相关资源
最近更新 更多