voidswapNums(int&x,int&y){cout<<"address of ref "<<&x<<" "<<&y<<"\n";intz=x;x=y;y=z;}intmain(){intfirstNum=10;intsecondNum=20;cout<<"Before swap: "<<"\n";cout<<firstNum<<" "<<secondNum<<"\n";cout<<"address of num "<<&firstNum<<" "<<&secondNum<<"\n";// Call the function, which will change the values of firstNum and secondNumswapNums(firstNum,secondNum);cout<<"After swap: "<<"\n";cout<<firstNum<<" "<<secondNum<<"\n";cout<<sizeof(firstNum)<<"\n";cout<<sizeof(secondNum)<<"\n";return0;}
classMyClass{// The classpublic:// Access specifierMyClass(){// Constructorcout<<"Hello World!";}};intmain(){MyClassmyObj;// Create an object of MyClass (this will call the constructor)return0;}
执行结果
1
HelloWorld
4. 方法默认参数
12345678910111213141516
voidmyFunction(stringcountry="Norway"){cout<<country<<"\n";}intmain(){myFunction("Sweden");myFunction("India");myFunction();myFunction("USA");return0;}// Sweden// India// Norway// USA
5. 继承
123456789101112131415161718192021
// Base classclassVehicle{public:stringbrand="Ford";voidhonk(){cout<<"Tuut, tuut! \n";}};// Derived classclassCar:publicVehicle{// 继承方式:publicpublic:stringmodel="Mustang";};intmain(){CarmyCar;myCar.honk();cout<<myCar.brand+" "+myCar.model;return0;}
// Base classclassMyClass{public:voidmyFunction(){cout<<"Some content in parent class.";}};// Another base classclassMyOtherClass{public:voidmyOtherFunction(){cout<<"Some content in another class.";}};// Derived class classMyChildClass:publicMyClass,publicMyOtherClass{};intmain(){MyChildClassmyObj;myObj.myFunction();myObj.myOtherFunction();return0;}
如果 MyClass 和 MyOtherClass 有同名函数,则允许继承但不允许调用
1234567891011121314151617181920212223242526272829
// Base classclassMyClass{public:voidmyFunction(){cout<<"Some content in parent class.";}};// Another base classclassMyOtherClass{public:voidmyFunction(){cout<<"Some content in another class.";}voidmyOtherFunction(){cout<<"Some content in another class.";}};// Derived classclassMyChildClass:publicMyClass,publicMyOtherClass{};intmain(){MyChildClassmyObj;myObj.myFunction();// err at compile timemyObj.myOtherFunction();// can execute properlyreturn0;}
// Base classclassMyClass{public:voidmyFunction(){cout<<"Some content in parent class.";}};// Another base classclassMyOtherClass{public:voidmyOtherFunction(){cout<<"Some content in another class.";}};// Derived classclassMyChildClass:privateMyClass,publicMyOtherClass{public:MyChildClass(){myFunction();// can execute properly}};intmain(){MyChildClassmyObj;myObj.myFunction();// 权限 = min(public, private) 也就是 private,err at compile timemyObj.myOtherFunction();// can execute properlyreturn0;}