- 有人把类说成是占用固定大小内存块的别名,其定义时不占用空间
#include<iostream> #include<string> using namespace std; class mycoach { public: string name="陈培昌"; int age=22; 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 0; }
输出结果:
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 0; }
输出结果:
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 0; }
- 命名空间
#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"); }
输出结果:
原文链接: https://www.cnblogs.com/saintdingspage/p/11934954.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/306482
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!