设为首页 加入收藏

TOP

c++学习笔记
2014-11-23 21:12:53 来源: 作者: 【 】 浏览:20
Tags:学习 笔记

1.常量--在类中使用常量


[cpp]
#include
using namespace std;

class A
{
private:
const int SIZE=18;
public:
A(){}
};
int main()
{
return 0;
}

#include
using namespace std;

class A
{
private:
const int SIZE=18;
public:
A(){}
};
int main()
{
return 0;
}上面的程序在编译时报错,类中用const定义的成员变量只能在构造函数中初始化进行初始化。


[cpp]
#include
using namespace std;

class A
{
private:
const int SIZE;
public:
A(int size):SIZE(size){}
// 常量变量只能在构造函数,普通方法无法设置SIZE
//编译无未能通过
void setSize(int size)
{
SIZE = size;
}
};

#include
using namespace std;

class A
{
private:
const int SIZE;
public:
A(int size):SIZE(size){}
// 常量变量只能在构造函数,普通方法无法设置SIZE
//编译无未能通过
void setSize(int size)
{
SIZE = size;
}
};2.函数返回值

[cpp]
#include
using namespace std;
char *getStr()
{
char p[] = "abc";
return p;
}
int main()
{
char *t = NULL;
t = getStr();
//输出乱码
cout< return 0;
}

#include
using namespace std;
char *getStr()
{
char p[] = "abc";
return p;
}
int main()
{
char *t = NULL;
t = getStr();
//输出乱码
cout< return 0;
}在getStr()中定义了一个局部字符数组,里面存放字符串"abc"。返回p的首地址,为什么输出的结果是乱码。因为在p是在getStr()内部定义的,局部变量是在内存的栈区分配的内存,其作用在函数体的内部。函数体结束后,栈区的容自动释放。所以在main函数输出的是乱码。


[cpp]
#include
using namespace std;
char *getStr()
{
char p[] = "abc";
printf("getStr()中p的地址:%d\n",p);
return p;
}
int main()
{
char *t = NULL;
printf("t的初始地址:%d\n",t);
t = getStr();
printf("函数调用后t的地址:%d\n",t);
return 0;
}

#include
using namespace std;
char *getStr()
{
char p[] = "abc";
printf("getStr()中p的地址:%d\n",p);
return p;
}
int main()
{
char *t = NULL;
printf("t的初始地址:%d\n",t);
t = getStr();
printf("函数调用后t的地址:%d\n",t);
return 0;
}\

在上面的程序可知t和p指向同一地址。但是在getStr()变量作用域只在函数体内。所以在main函数中输出与p同一地址的内容是乱码
[cpp]

 
 
 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj 2109 Power of Cryptography(.. 下一篇hdu 1272 小希的迷宫 (并查集+最..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C/C++ 类模板与模板 (2025-12-27 01:49:52)
·C语言 模板化<templ (2025-12-27 01:49:49)
·C/C++模板类模板与函 (2025-12-27 01:49:46)
·如何理解c语言指针和 (2025-12-27 01:19:11)
·为什么C标准库没有链 (2025-12-27 01:19:08)