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 类型呢,应该报错啊??
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;
}