日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++(四)——类和对象(下)

發布時間:2025/3/21 c/c++ 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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++(四)——类和对象(下)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。