【发布时间】:2009-07-07 14:35:48
【问题描述】:
我有以下代码:
Some functions:
A::A(int i_a) {cout<<"int Ctor\n";} //conversion constructor
void h(double d) {cout<<"double param\n";} //f1
void h(A a) {cout<<"A param\n";} //f2
在主函数中:
h(1);
h(1) 调用的函数是 f1。
我的问题是它为什么选择这样称呼它。 1 是一个 int,因此需要 隐式转换为双精度。它可以很容易地将 int 转换为 A 使用 上面定义的转换构造函数。为什么我没有收到错误消息?什么是 强制转换的优先规则?
注意我已经在上面发布了我认为有必要回答这个问题的代码, 但下面我发布了整个代码:
#include <iostream>
using namespace std;
class B;
class A {
public:
explicit A(const B&) {cout<<"Ctor through B\n";}
A() {cout<<"Default Ctor\n";}
A(int i_a) {cout<<"int Ctor\n";}
operator int() {cout<<"A => int\n"; return 2;}
};
class B {
public:
operator A() const {cout<<"B => A\n"; A a; return a;}
};
void h(double d) {cout<<"double param\n";}
void h(A a) {cout<<"A param\n";}
void f(const A& a)
{
cout<<"f function\n";
//Without the const it will never try to convert
}
void main()
{
B b;
cout <<"-----------------\n";
f(b);
cout <<"-----------------\n";
h(1);
}
【问题讨论】:
-
发布代码时。不要添加行号 - 如果不进行额外编辑,就无法编译它。如果您想突出显示行号,请使用注释。
-
编辑的行号输出。
-
作为旁注,我不会将“A::A(int i_a)”称为转换构造函数,只是 A 的构造函数,它恰好将 int 作为参数。此外,使用其确切参数调用 h(任何 h)总是好的。如果它需要一个 A(第二个函数),那么为什么不给它一个 A 呢?例如 h(A(1));
-
@Daniel- 我试图更好地理解 c++ 是如何工作的。显然上面的代码并不是最优的。
-
@Daniel: "A::A(int i_a)" 被称为转换构造函数,因为它会将整数隐式转换为 A 对象。如果您在 ctor 定义前添加关键字“explicit”,则此隐式转换行为将被删除——然后,它“只是”A 的构造函数,恰好将 int 作为参数。
标签: c++