C++随笔(四)
1.成员函数的定义
两种形式:一种是在类声明中只给出成员函数的原型,函数体在类的外部定义。
void point::setposit(int a, int y)
{ x=a; y=b;}
int point::getx( )
{ return x; }
int point::gety( )
{ return y; }
另一种是内置函数:将成员函数定义在类内部,即内置函数,(一种是直接将函数定义在内部,将函数放在类定义体外,在函数定义体之前冠以“inline”,起到内置函数的作用。)
class point { private: int x, y; public: void Setposit(int, int); int getx( ); int gety( ); }; inline void point::setposit(int a, int y) { x=a; y=b; } inline int point::getx( ) { return x; } inline int point::gety( ) { return y; }
2.拷贝构造函数
#include <iostream.h> class point { int x,y; public: point(int a,int b) { x=a; y=b; } void print() { cout<<x<<" "<<y<<endl;} }; int main() { point p1(30, 40); point p2(p1); point p3=p1; p1.print(); p2.print(); p3.print(); int x; cin >> x; return 0; }
3.对象数组
#include <iostream.h> class exam { public: int x; public: exam(int n) { x=n; } int get_x() { return x; } }; int main() { exam ob[4]={11,22,33,44}; for(int i=0; i<4; i++) cout<<ob[i].get_x()<<‘ ‘; cout <<endl; return 0; }
#include <iostream.h> class point { private: int x,y; public: point() { x=5; y=5; } point(int a,int b) { x=a; y=b; } int getx() { return x; } int gety() { return y; } }; int main() { point op(3, 4); cout<<"op x="<<op.getx()<<endl; cout<<"op y="<<op.gety()<<endl; point op_array[20]; cout<<"op_array[1] x="<<op_array[1].getx()<<endl; cout<<"op_array[1] y="<<op_array[1].gety()<<endl; int x; cin >> x; return 0; }
4.参数传递:
#include <iostream.h> class tr { int i; public: tr(int n) {i=n;} void set_i(int n) {i=n;} int get_i() {return i;} }; void sqr_it(tr ob) { ob.set_i(ob.get_i()*ob.get_i()); cout<<"copy of obj has i value of "<<ob.get_i()<<"\n"; } int main() { tr obj(10); sqr_it(obj); cout<<"But, obj.i is unchanged in main:"<<obj.get_i() << endl; return 0; }
值变化
#include <iostream.h> class tr { int i; public: tr(int n) {i=n;} void set_i(int n) {i=n;} int get_i() {return i;} }; void sqr_it(tr& ob) { ob.set_i(ob.get_i()*ob.get_i()); cout<<"copy of obj has i value of "<<ob.get_i()<<"\n"; } int main() { tr obj(10); sqr_it(obj); cout<<"But, obj.i is unchanged in main:"<<obj.get_i()<<endl; return 0; }
5.静态数据变量
“类名::”
访问静态的数据成员。
#include <iostream.h> class Student { static int count; int StudentNo; public: Student() { count++; StudentNo=count; } void print() { cout<<"Student"<<StudentNo<<" "; cout<<"count="<<count<<endl; } }; int Student::count=0; int main() { Student Student1; Student1.print(); cout<<"-----------------------\n"; Student Student2; Student1.print(); Student2.print(); cout<<"-----------------------\n"; Student Student3; Student1.print(); Student2.print(); Student3.print(); cout<<"-----------------------\n"; Student Student4; Student1.print(); Student2.print(); Student3.print(); Student4.print(); return 0; }
7.友元
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。