918_2_

1.  已知类A B  以下四个 哪些可以 哪些有错

class A
{ };
class B:public A
{ };
A* pa = new B;  //  对
B* pb = new A;  //  错
A a = B b;      //  对 
B b = A a;      //  错

解答: 父类可以接受子类   子类没法接受父类

2.  如下 输出的是:

class A
{
public:
    virtual void fun1(int a = 2)
    {
        cout<<a<<"A"<<endl;
    }
    virtual void fun2()
    {
        cout<<"A"<<endl;
    }
};
class B:public A
{
public:
    virtual void fun1(int a = 3)
    {
        cout<<a<<"B"<<endl;
    }
    virtual void fun2()
    {
        cout<<"B"<<endl;
    }
};
int main()
{
    A* pa = new B;
    pa->fun1();
    pa->fun2();
    return 0;
}

解答: 输出的 2 B B          //因为是虚函数 所以都调用的B类中的函数  而虚函数的形参定义是不能改变的 因此依然是A中的 a = 2

3. float 32 bit  假设无参考文档 如何获得其中浮点的表示结构        如何输出32个bit (用的移位 (x>>n)&1  但是应该有更好的办法 int指针??)

void printBin(void * p){
    bitset<32> bs(*(unsigned int*)p);
    cout<<bs<<endl;
}

    float s = 1.5;
    int p = (int&)s;
    for(int i = 0;i < 32;i++)
        cout<<(p >> i &1);

4. string类的构造函数 重载 = 

class Str 
{
    friend ostream& operator<< (ostream& os,const Str& s);
public:
    Str(const char* p = NULL);
    Str(const Str& s);
    ~Str();
    Str& operator = (const Str& s);
    char* pStr;
    int len;
};
Str::Str(const char* p /* = NULL */)
{
    if (p == NULL)
    {
        len = 0;
        pStr = new char[1];
        *pStr = '\0';
    }
    else
    {
        len = strlen(p);
        pStr = new char[len + 1];
        strcpy(pStr,p);
    }
}
Str::Str(const Str &s)
{
    len = s.len;
    pStr = new char[len + 1];
    strcpy(pStr,s.pStr);
}
Str::~Str()
{
    delete []pStr;
}

Str& Str::operator = (const Str& s)
{
    if (pStr != s.pStr)
    {
        delete []pStr;
        len = s.len;
        pStr = new char[len + 1];
        strcpy(pStr,s.pStr);
    }
    return *this;
}
ostream& operator<<(ostream& os,const Str& s)
{
    os<<s.pStr;
    return os;
}
posted @ 2012-09-19 09:18  Itachi7  阅读(171)  评论(0编辑  收藏  举报