-
string 初始化和賦值方式
查看全部 -
堆中實例對象注意判斷實例是否成功
查看全部 -
堆中訪問數據成員或者賦值
查看全部 -
堆實例的對象訪問
第二部分
查看全部 -
棧實對象用點訪問
查看全部 -
堆實例對象
查看全部 -
實例化對象
棧
查看全部 -
NULL 都要大寫,
public 和private 都是小寫。
記得冒號
定義函數? 參數可以是參數形式+形參?
返回類型。
使用new 實例化對象正對類的使用。還需要理解
#include <iostream>
#include <string>
using namespace std;
/**
? * 定義類:Student
? * 數據成員:m_strName
? * 數據成員的封裝函數:setName()、getName()
? */
class Student
{
public:
? ? // 定義數據成員封裝函數setName()
? ?void setName(string str)
? ?{
? ? ? ?m_strName=str;
? ?}
? ??
? ??
? ? // 定義數據成員封裝函數getName()
? ?string getName()
? ?{
? ? ? ?return m_strName;
? ?}
? ??
? ??
//定義Student類私有數據成員m_strName
private:
string m_strName;
};
int main()
{
? ? // 使用new關鍵字,實例化對象
Student *str = new Student();
? ? // 設置對象的數據成員
str->setName("慕課網");
? ? // 使用cout打印對象str的數據成員
? ? cout<<str->getName()<<endl;
? ? // 將對象str的內存釋放,并將其置空
delete str;
str= NULL;
return 0;
}
查看全部 -
?方法和連接
查看全部 -
1.析構函數
????????定義格式? ? ? ?~類名()? 括號內不允許加任何參數
2.特性總結
????????若未定義,則自動生成;
????????在對象銷毀時自動調用;
????????無返回值,無參數,無重載;查看全部 -
1.拷貝構造函數
2.注意
3.構造函數分類查看全部 -
1.拷貝構造函數?
在對象復制或者作為參數進行傳遞時進行調用。查看全部 -
在頭文件中聲明函數時設置默認值;
在函數定義時進行初始化;查看全部 -
1.默認構造函數
? ?在實例化對象時,無參數的構造函數或者有參數但參數具有默認值的構造函數。
2.構造函數初始化列表
? 1- 定義方式:
? Student():m_strName("james"),m_iAge(15){};
? 2-使用特點:
? 初始化列表先于構造函數執行;
? 初始化列表只能用于構造函數;
? 初始化列表可以同時初始化多個數據成員。
3.初始化列表的必要性
?對常量設置初始值時可采用 初始化列表的方式來防止 語法錯誤。查看全部 -
示例代碼:
1.teacher.h? 頭文件代碼:? //對數據成員和結構函數進行聲明
#include<iostream>
#include<string>
using namespace std;
class Teacher
{
public:
Teacher();
Teacher(string name, int age);
void setName(string name);
string getName();
void setAge(int age);
int getAge();
private:
string m_strName;
int m_iAge;
};
2.teacher.cpp? ?//對結構函數和功能函數進行定義
#include<iostream>
#include<stdlib.h>
#include<string>
#include "teacher.h"
Teacher::Teacher()
{
m_strName = "james";
m_iAge = 5;
cout << "Teacher()" << endl;
}
Teacher::Teacher(string name, int age)
{
m_strName = name;
m_iAge = age;
cout <<"Teacher(string name, int age)" << endl;
}
void Teacher::setName(string name)
{
m_strName = name;
}
string Teacher::getName()
{
return m_strName;
}
void Teacher::setAge(int age)
{
m_iAge = age;
}
int Teacher::getAge()
{
return m_iAge;
}
3.test.cpp? 代碼: //主函數結構,對象實例化及調用
#include<iostream>
#include<stdlib.h>
#include<string>
#include "teacher.h"
using namespace std;
int main(void)
{
Teacher t1;
Teacher t2("lucy", 15);
cout << t1.getName() << " " << t1.getAge() << endl;
cout << t2.getName()<< " " << t2.getAge() << endl;
system("pause");
return 0;
}
4.注意事項
? 構造函數默認值的設置,保證多個函數重載時不會產生沖突。
構造函數在對象實例化時被調用。查看全部
舉報