• 有人把类说成是占用固定大小内存块的别名,其定义时不占用空间
#include<iostream>
#include<string>
using namespace std;
class mycoach
{
public:
string name="陈培昌";
int age=;
private:
string favorite = "和丁大锅在一起";
public:
void introduce()
{
cout << "大家好,我是" + name << "爱好是:" + favorite << endl;
}
}; void main()
{
mycoach cpc;
cout << "大家好,我是"+cpc.name<<endl;
cpc.introduce();
getchar(); }

输出结果:

  • 常见错误----为什么成员函数很重要
#include<iostream>
#include<math.h>
using namespace std;
class mycircle
{
public:
double radius;
double mypie = 3.1415926;
double s = radius*radius*mypie;
}; int main()
{
mycircle circle;
cout << "请输入半径:";
cin >> circle.radius;
cout << "OK半径是: " << circle.radius << " 那么圆的面积是:"<<endl;
cout << circle.s << endl;
system("pause");
return ;
}

输出结果:

what hell that do......究其原因,乃是,类定义时就为mycircle的成员属性s就分配了一块空间,其值是乱码

即使在main函数中为radius赋值,然而这对s并无任何影响,所以其值为乱码,所以计算面积s不得不使用一成员函数

#include<iostream>
#include<math.h>
using namespace std;
class mycircle
{
public:
double radius;
double mypie = 3.1415926;
//double s = radius*radius*mypie;
public:
double gets()
{
return radius*radius*mypie;
}
}; int main()
{
mycircle circle;
cout << "请输入半径:";
cin >> circle.radius;
cout << "OK半径是: " << circle.radius << " 那么圆的面积是:"<<endl;
cout << circle.gets()<< endl;
system("pause");
return ;
}

输出结果:

namespace的用途:比起C来说,C++的函数库十分丰富,有可能遇到库函数名撞库的现象,所以需要namespace来区分

我们常见的namesapce 是标准命名空间即 using namespace std,如果未声明代码要使用的命名空间,那么可以通过这种方法引入

int main()
{
mycircle circle;
std::cout << "请输入半径:";
std::cin >> circle.radius;
std::cout << "OK半径是: " << circle.radius << " 那么圆的面积是:"<<std::endl;
std::cout << circle.gets()<< std::endl;
system("pause");
return ;
}
  • 命名空间
#include "iostream"
#include<string>
using namespace std;
namespace cjbefore1014
{
string comment = "懂事,可爱的搏击弟弟一口一个哥";
}
namespace cjafter1014
{
string comment = "冷酷,无情,自私,过河拆桥,傲慢,不可理喻,白眼狼";
} void main()
{
using namespace cjbefore1014;
cout << "once upon the time:有这样一个搏击弟弟" << endl;
cout << "在2019年10月14日以前" << "他是一个" << endl;
cout <<comment << endl;
using namespace cjafter1014;
cout << "在2019年10月14日以后" << "他是一个" << endl;
cout << cjafter1014::comment << endl;
system("pause");
}

输出结果:

最新文章

  1. iOS中数据库应用基础
  2. iOS 统计App 的代码总行数
  3. Dual Number
  4. linux下emacs配置文件
  5. 为benchmarksql的PostgreSQL java驱动进行升级
  6. BZOJ 4443: [Scoi2015]小凸玩矩阵 二分图最大匹配+二分
  7. CentOS服务器的16个监控命令
  8. 【XMLRPC实现跨语言编程】Tcl &lt;----&gt; python
  9. Java中各种排序算法
  10. [Theano] Theano初探
  11. DBS小结
  12. 根据模板导出Excel报表并生成多个Sheet页
  13. HTTP长连接、短连接使用及测试
  14. go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
  15. sqlsever存储过程配合代理作业自动定时建表
  16. 基于jmeter的性能测试平台(一)分布式jmeter搭建
  17. [java]类初始化挺有意思的题目
  18. 【python】声明编码的格式
  19. c#.net基础
  20. &lt;转&gt;jmeter(七)定时器

热门文章

  1. linux下使用Oracle常用命令
  2. [转帖]8个优秀Docker容器监控工具,收藏了
  3. 剑指offer57:二叉树的下一个结点
  4. vscode配置phpxdebug
  5. 笔记-9:使用random库生成随机数
  6. python多任务基础
  7. c语言 运算器
  8. 【BFS】斗地主
  9. QLineEdit的信号函数
  10. (转)从0移植uboot (四) _点亮调试LED