从今天开始学好C++

1.const int x,y;

 int const x,y;

是等价的xy都是只读变量。

2.

#include <iostream>

using namespace std;
class Base
{
public:
void show()const
{
cout<<"const function"<<endl;
}
void show()
{
cout<<"normal function"<<endl;
}
};

int main()
{
Base b;
b.show();
const Base c;
c.show();
return 0;
}

const 修饰this是可以重载成员函数的。而且const的对象不可以调用费const的成员函数。

3

书上说,

int & modify()const
{

return x;
}这样是有效的,有可能改变const类型的对象,但在gcc中测试无效。

error: invalid initialization of reference of type 'int&' from expression of type 'const int'|

 

4

 1 #include <iostream>
 2 
 3 using namespace std;
 4 class Base
 5 {
 6 public:
 7     void modify()
 8     {
 9         x = 250;
10         cout<<"i am called!"<<endl;
11     }
12 private:
13     int x;
14 public:
15 
16     Base()
17     {
18          x = 0;
19     }
20     void show()
21     {
22         cout<<x<<endl;
23     }
24 
25 };
26 
27 class Drive :public Base
28 {
29 
30 
31 public:
32     void modify()
33     {
34        1. static_cast<Base>(*this).modify();
35         2.((Base)(*this)).modify();
36         3.Base::modify();
37     }
38 
39 };
40 int main()
41 {
42     Drive d;
43     d.show();
44     d.modify();
45     d.show();
46     return 0;
47 }

钱两种均未修改Base::x的值,但是基类的modify函数被调用额。

5

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
const int x=6;

*((int *)(&x) ) =8;

printf("%d,%d\n",&x,(int * )&x);
printf("%d,%d\n",x,*(int * )&x);
return 0;
}

在codeblocks下的c工程和++工程的结果不一致。不晓得为甚。

 6.重载或者定义operator=时,注意自我复制。

class Base
{
    char * p ;

public:
    Base(const char * p):p(new char[strlen(p)+1])
    {
        strcpy(this->p,p);
    }
    const Base & operator= (const Base & b)
    {
        delete p;
        p = new char[strlen(b.p)+1];
        strcpy(p,b.p);
        return * this;

    }
    void show()
    {
        cout<<p<<endl;
    }
};

1.加入判断

if( this == &b)
return * this;

2.调整顺序

3.copy-and-swap

7.单个对象可能拥有一个以上的地址,父类指针和同类指针指向他的地址很可能不一样。

 1 class Base
 2 {
 3     int x;
 4 
 5 };
 6 class Base2
 7 {
 8     int y;
 9 };
10 class Derived:public Base2 ,public Base
11 {
12     int z;
13 };
14 
15 
16 int main()
17 {
18     Derived a;
19     Base2 *p2 = &a;
20     Base * p1 = &a;
21     cout<<int(p2)<<"  "<<int(p1)<<endl;
22     return 0;
23 }

8.转型会产生副本

1     Base x;
2     x.x = 5;
3     (static_cast<Base>(x)).change(2);
4     x.show();

第三行修改的只是x在转型时产生的临时副本,加入直接赋值错误: using temporary as lvalue [-fpermissive]|。

 

 

posted on 2013-07-08 19:10  珞珈風哥  阅读(366)  评论(0编辑  收藏  举报

导航