c++类型转换解决思路
c++类型转换
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A(int a):x(a)
{
}
private:
int x;
};
class B{
public:
B(int a,int b) :Aa(a),y(b)
{
}
private:
A Aa;
int y;
};
int main()
{
B b(2,3);
return 0;
}
以上能编译通过!
B(int a,int b) :Aa(a),y(b) int 咋能赋给A 类型呢,应该报错啊??
------解决方案--------------------
隐式转换了, explicit A(int a):x(a)就过不了了
------解决方案--------------------
那是构造函数初始化。
------解决方案--------------------
B(int a,int b) :Aa(a),y(b)用的初始化列表,用a作参数调用了A类的constructor,给2个类的constructor都加一句话,马上就清楚了.
run一下下面的代码
------解决方案--------------------
隐式转换,最好加explicit 禁止
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A(int a):x(a)
{
}
private:
int x;
};
class B{
public:
B(int a,int b) :Aa(a),y(b)
{
}
private:
A Aa;
int y;
};
int main()
{
B b(2,3);
return 0;
}
以上能编译通过!
B(int a,int b) :Aa(a),y(b) int 咋能赋给A 类型呢,应该报错啊??
c++
------解决方案--------------------
隐式转换了, explicit A(int a):x(a)就过不了了
------解决方案--------------------
那是构造函数初始化。
------解决方案--------------------
B(int a,int b) :Aa(a),y(b)用的初始化列表,用a作参数调用了A类的constructor,给2个类的constructor都加一句话,马上就清楚了.
run一下下面的代码
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A(int a):x(a)
{
cout << "init A" << endl;
}
private:
int x;
};
class B{
public:
B(int a,int b) :Aa(a),y(b)
{
cout << "init B" << endl;
}
private:
A Aa;
int y;
};
int main()
{
B b(2,3);
return 0;
}
------解决方案--------------------
隐式转换,最好加explicit 禁止