gpt4 book ai didi

c++ - 构造包含类型的参数

转载 作者:行者123 更新时间:2023-11-28 01:40:13 24 4
gpt4 key购买 nike

我不确定这里使用的术语是什么,这使得查找相关信息变得困难。在我的代码中让我感到惊讶之后(点击编译,意识到我忘记更新一些地方......它编译并且运行没有错误),我做了一个简单的例子来验证它。

我有一个包含另一个类的容器类。它有一个构造函数,该构造函数采用对其包含的类的 const 引用。我有另一个函数,它采用对容器类的 const 引用。我可以将包含类的一个实例传递给该函数,它会自动为我创建一个临时的容器类。也没有警告 (-Wall -pedantic -Wextra -Werror)。

#include <iostream>

class A { // Contained class.
public:
A(int i) : a_number_(i) {}
void print() const { std::cout << a_number_ << "\n"; }
private:
int a_number_;
};

class A_Container { // Container class.
public:
~A_Container() { delete a_; }
A_Container(const A& a) : a_(new A(a)) { std::cout << "I was called!\n"; }
const A& getA() const { return *a_; }
private:
A* a_;
};

void foo(const A_Container& container) { // This func takes a container...
container.getA().print();
}

int main() {
A a(147);
foo(a); // ...but I'm passing it the contained class.
return 0;
}

输出:

I was called!
147

这叫什么?这种类型的转换要起作用有什么要求?

我可以看到它有意义让它起作用,但是除了编译器的魔法之外还有更多的东西吗?

编辑:

有用的链接:What does the explicit keyword mean?

最佳答案

如果 C++ 具有未标记为 explicit 的单参数构造函数,C++ 将为您隐式构造容器类。为了避免这种意外发生,通常将一元构造函数限定为显式:

explicit Container(const A& a);

现在它不会编译(这在某些情况下是一种改进,以避免在实际错误或不需要的情况下意外地“运行”代码)。

关于c++ - 构造包含类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47482030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com