gpt4 book ai didi

c++ - 构造函数的类型是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:32 24 4
gpt4 key购买 nike

我知道构造函数没有返回类型。虽然我想知道,那么构造函数的类型是什么?构造函数有类型吗?

我试过了

struct A { A() {} };

template <typename A> struct foo;

int main() { foo< decltype(&A::A) > f; }

得到错误(gcc)

prog.cc: In function 'int main()':
prog.cc:5:32: error: taking address of constructor 'constexpr A::A(A&&)'
5 | int main() { foo< decltype(&A::A) > f; }
| ^
prog.cc:5:35: error: template argument 1 is invalid
5 | int main() { foo< decltype(&A::A) > f; }
| ^

...好吧,我不能接受地址。这也失败了:

int main() { foo< decltype(A::A) > f; }

prog.cc: In function 'int main()':
prog.cc:5:32: error: decltype cannot resolve address of overloaded function
5 | int main() { foo< decltype(A::A) > f; }
| ^
[...]

这可能只是一个非常困惑的错误消息,由与上述相同的原因(无法获取构造函数的地址)引起,我不知道还能尝试什么..

构造函数的类型是什么?

如果它没有类型,那它是什么?当然不是 A (member_function)()

PS:澄清一下我的困惑:cpprefernce

Constructor is a special non-static member function of a class that is used to initialize objects of its class type.

我的逻辑是这样的:成员函数有一个类型,构造函数是特殊类型的成员函数,因此它们应该有一个类型。我知道推理有缺陷,但为什么呢?

最佳答案

我认为这些来自 C++ 17 标准的引用是相关的(15.1 构造函数)

1 Constructors do not have names....

2 A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation (8.5.1.3) will cause a constructor to be called to initialize an object. [ Note: For initialization of objects of class type see 15.6. — end note ]

10 A return statement in the body of a constructor shall not specify a return value. The address of a constructor shall not be taken.

关于c++ - 构造函数的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57217858/

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