您的位置:首页 > 编程语言 > C语言/C++

C++功在不舍(2012.07.07)

2012-07-07 18:08 134 查看
驽马十驾,功在不舍。

一、指针

1.this指针

this 变量记录每个对象的内存地址,然后通过间接访问运算符->访问该对象的成员。this指针的创建和删除由编译器来完成。

头文件中类的定义:

class A
{
public:
A();
~A();
int get()const{return i;}
//the function of the assignment of *i
void set(int x)
{this->i=x;
cout<<"this指针的地址"<<this<<endl;}
private:
int i;
};
.cpp文件中的写法

A::A()
{
cout<<"构造函数执行中……"<<endl;
this->i=1000;     //  in the scope of A
}
A::~A()
{
cout<<"析构函数执行中……"<<endl;
}
int main()
{
A a;//在栈中创建空间
cout<<a.get()<<endl;
//cout<<this->                                 To use this in the main function makes no sense.
a.set(10);
cout<<a.get()<<endl;
return 0;
}


2.删除一个指针后,一定要将该指针设为空指针。delete指针,只会释放它所指向的内存空间,不会删除指针。指针仍然存在着,并且依然指向原来的内存空间,但由于内存空间已经不存在了,所以这样做就会引起错误。

#include <iostream>
using namespace std;
int main()
{
int* p=new int;
cout<<"the address of p is:"<<p<<endl;
*p=3;
delete p;
cout<<"the address of p after deleting it is:"<<p<<endl;
int* p1=new int;
*p1=4;
cout<<"the address of p after int* p1 is:"<<p<<endl;
cout<<"the address of p1 is:"<<p1<<endl;
}



结果发现delete p后,没有令p=0;p and p1保存的都是造成新开辟的内存空间的地址。

3.指针运算。

(1)解决心中的疑问。

int* p=new int;

p++;

++为自加操作,自加并不总是加1。因p为int型指针,所以此处的自加操作为+4.



4.指针的不同类型。

(1)常量指针。int *const p;该指针只能被初始化,不能被赋值。p++;或者p=p+2;的操作都是不可行的。

(2)指向常量的指针。const int* p;指针所指向的证书不能被修改,但是指针可以被修改。

(3)指向常量的常指针。const int *const p;指针指向的整数不能被修改,指针也不能被修改。

二、引用

{
int x=1;
int &x_eq=x;
cout<<"the value of x="<<x<<endl;
cout<<"the value of x_eq="<<x_eq<<endl;
cout<<"the address of x"<<&x<<endl;
cout<<"the address of x_eq"<<&x_eq<<endl;
return 0;
}



???引用的意义到底是什么啊???

5.函数的参数传递

int change(int a, int b)
{
int c;
c=a;
a=b;
b=c;
return a,b;
}
int main()
{
int a=3,b=4;
change(a,b);
cout<<"a="<<a<<"b="<<b<<endl;
return 0;
}
执行的结果仍然是a=3,b=4;范磊老师的《从新手到高手C++全方位学习》给出的解释是(引号中内容来自范磊老师的书):“传递a和b的值给函数change()时,编译器会自动在栈中创建该值的拷贝,因此change()函数在对传入的参数进行交换时,交换的其实是a,b的副本。在函数交换完成并返回一个值时,a,b的副本,以及change()函数的局部变量c将按照栈的先进后出原则依次从栈中弹出。这会导致在用cout进行对a
and b的输出时,a b 的副本已经不再存在于栈中,它们已经被释放,输出的只能是main()函数中未交换过的a 和b!”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: