C++(四)——类和对象(下)
生活随笔
收集整理的這篇文章主要介紹了
C++(四)——类和对象(下)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
this指針的用途
#include<iostream> using namespace std; //解決名稱沖突//返回對象本身 *this class Person { public:int age;Person(int age) {//this指針指向的是被調用的成員函數所屬的對象this->age = age;}Person & personAddage(Person &p) {this->age += p.age;return *this;}}; void test01() {Person p1(18);cout << "p1的年齡為:" << p1.age << endl;}void test02() {Person p1(10);Person p2(10);//鏈式編程思想p2.personAddage(p1).personAddage(p1).personAddage(p1);cout << "p2的年齡為:" << p2.age << endl; }int main() {//test01();test02(); }空指針訪問成員函數
#include<iostream> using namespace std; //空指針可以調用成員函數 class Person { public:void showClassName() {cout << "this is Person class" << endl;}void showPersonAge() {if (this == NULL)//提高健壯性,為NULL直接返回return;cout << "age = " << m_age << endl;}int m_age;}; void test01() {Person* p = NULL;p->showClassName();//p->showPersonAge();//報錯原因傳入指針為NULL} int main() {test01();return 0; }const修飾成員函數
#include<iostream> using namespace std; //常函數,常對象 class Person { public://this指針的本質是指針常量 指針指向的是不可以修改的//const Person * const this//在成員函數后面加const,修飾的是this指向,讓指針指向的值也不能修改void showPerson() const{m_b = 100;//m_a = 100;//this = NULL//this指針不可以修改指針的指向}void fun() {}int m_a;mutable int m_b;//特殊變量 即使在常函數中 也可以修改 必須加mutable };void test01() {Person p;p.showPerson();} void test02() {const Person p;//在對象前加const,變為常對象//p.m_a = 100;p.m_b = 100;//因為加了mutable,所以可以修改p.showPerson();//常對象只能調用常函數//p.fun()//常對象不能調用普通成員函數,普通成員函數可以修改成員變量 }int main() {test02();return 0; }全局函數做友元
#include<iostream> using namespace std; class Building {//goodGay全局函數是Building的友元,可以訪問私有成員friend void goodGay(Building* building); public:Building() {m_SittingRom = "客廳";m_BedRoom = "臥室";}string m_SittingRom; private:string m_BedRoom;}; void goodGay(Building *building) {cout << "好基友的全局函數 正在訪問" << building->m_SittingRom << endl;cout << "好基友的全局函數 正在訪問" << building->m_BedRoom << endl;} void test01() {Building building;goodGay(&building); }int main() {test01(); }類做友元
#include<iostream> using namespace std; class Building; class GoodGay { public:GoodGay();void visit();//參觀函數訪問building中的屬性Building* building;}; class Building {//GoodGay是本類的友元,可以訪問私有成員friend class GoodGay; public:Building();string m_SittingRoom; private:string m_BedRoom;};//類外寫成員函數 Building::Building() {m_SittingRoom = "客廳";m_BedRoom = "臥室";}GoodGay::GoodGay() {building = new Building;} void GoodGay::visit() {cout << "好基友正在訪問" << building->m_SittingRoom << endl;cout << "好基友正在訪問" << building->m_BedRoom << endl; } void test01() {GoodGay gg;gg.visit(); }int main() {test01();return 0; }總結
以上是生活随笔為你收集整理的C++(四)——类和对象(下)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++(三)——类和对象(上)
- 下一篇: 机器学习(一)——熟悉tensorflo