c++ - 隐式调用构造函数

标签 c++ class implicit-conversion

我有这个考试问题:

Bar can be properly constructed with ...

我必须选择正确的选项:

class Bar{
public:
    Bar(std::string);
    Bar(int a=10,double b=7.10, char c='e');
};

a) Bar{4,2,6};

b) Bar{"xyz",2};

c) Bar(true,false);

d) Bar{5,"abc"};

e) Bar();

我认为它肯定可以用 a) 来构造(从 intchar 的隐式转换)。我还认为不应该用 b) 来构造和d)因为没有从 const char* 进行隐式转换至double 。我认为Bar()是一个函数原型(prototype),所以这是不可能的。然后c) true 和 false 可以转换为 intdouble 。所以我的想法是:a)d)可以构建Bar正确地。

我说得对吗?有经验的人可以证实这一点吗?

最佳答案

I think that Bar() is function prototype so it's out of question.

不,Bar::Bar(int =10,double =7.10, char ='e') 声明了一个默认构造函数,因此 Bar() 完全有效并且将 use the above default ctor .

同样,Bar{4,2,6};Bar(true, false) 也将使用默认构造函数。

class Bar{
public:
Bar(std::string){}
Bar(int a=10,double b=7.10, char c='e'){
    std::cout <<"default " << std::endl; 
}
};
int main()
{
    Bar(true, false); //uses default ctor
    Bar();           //uses default ctor see demo link below
    Bar{1,2,3};      //uses default ctor

}

Demo

关于c++ - 隐式调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74863809/

相关文章:

c++ - 单元测试函数对象是否被调用

objective-c - 是否可以为类别声明第二个@interface?

c++ - 如何摆脱重复编写 namespace_name::inside 类头

string - Scala 中的条件隐式函数

c++ - 二维索引的良好哈希函数

c++ - 字符串类实现的差异

c# - 为什么 C# 中的这种隐式类型转换会失败?

c++ - 是否可以为 std::array 定义隐式转换运算符?

c++ - fork 进程时std::cin不阻塞

Python 列表类 __contains__ 方法功能