首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++类型转换解决思路

2013-01-22 
c++类型转换#include iostream #include stringusing namespace stdclass A{public:A(int a):x(a){}p

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;
}

[解决办法]
隐式转换,最好加explicit 禁止 

热点排行