c++学习笔记之构造函数
生活随笔
收集整理的這篇文章主要介紹了
c++学习笔记之构造函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
c++構造函數?
構造函數的目的就是對數據成員進行初始化,構造函數可以在類內定義也可以在類外定義,在類內定義和定義一般函數的方法基本一致,在類外構造函數需要注意的一點就是構造函數沒有返回類型。在使用構造函數的時候需要注意的幾點
(1)每建立一個對象,就調用一次構造函數
(2)構造函數沒有返回值,因此也沒有類型,因此不需要再定義構造函數是聲明類型。
(3)構造函數不需要用戶調用,也不能被用戶調用。
(4)可以用一個類對象初始化另一個類對象。
(5)構造函數的名字必須與類名同名。
下面是帶參數的構造函數代碼運行示例
以下代碼功能均是計算長方體的體積
#include<iostream> using namespace std; class box {public:box(int,int,int);int volume();private:int height;int width;int length; }; box::box(int h,int w,int len) {height=h;width=w;length=len; } int box::volume() {return(height*width*length); } int main() {box box1(12,25,30);cout<<"the volume of box1 is"<<box1.volume()<<endl;box box2(15,30,21);cout<<"the volume of box2 is"<<box2.volume()<<endl;return 0; }當然除了以上方法還能用函數初始化表對數據成員進行初始化。下面這段程序是構造函數的重載和用參數初始化表初始數據成員的例子
構造函數重載需要注意的幾點
(1)如果在建立對象是選用的無參構造函數應該這樣定義BOX box1而不是這樣定義 BOX box1();
(2)一個類可以包含多個構造函數,但是對于每一個對象來說,建立對象只執行其中一個構造函數。
附代碼
#include<iostream> using namespace std; class box {public:box();//定義一個無參構造函數 box(int h,int w,int len):height(h),width(w),length(len){}; //定義一個有參的構造函數,用參數的初始化表對數據成員初始化 int volume();private:int height;int width;int length; }; box::box() //在類外定義無參構造函數box {height=10;width=10;length=10; } int box::volume() {return (height*width*length); } int main() {box box1; // 建立對象box1不指定實參 注意寫法box1()不對 cout<<"the volume of box1 is"<<box1.volume()<<endl;box box2(15,30,25); //建立對象box2指定3個實參 cout<<"the volume of box2 is"<<box2.volume()<<endl;return 0; }進一步改進:使用默認參數的構造函數需要注意的幾點
(1)應在聲明構造函數時指定默認值,不能只在定義構造函數時指定默認值。、
(2)最好不同時使用構造函數的重載和有默認參數的的構造函數比如? box() box(int,int=10,int=10)(有一個參數不是默認參數)容易出現歧義
#include<iostream> using namespace std; class box {public:box(int h=10,int w=10,int len=10);int volume();private:int height;int width;int length;} ;box::box(int h,int w,int len){height=h;width=w;length=len;}int box::volume(){return (height*width*length);}int main(){box box1;cout<<"the volume of box1 is"<<box1.volume()<<endl;box box2(15);cout<<"the volume of box2 is"<<box2.volume()<<endl;box box3(15,30);cout<<"the volume of box3 is"<<box3.volume()<<endl;box box4(15,30,20);cout<<"the volume of box4 is"<<box4.volume()<<endl;}?
總結
以上是生活随笔為你收集整理的c++学习笔记之构造函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言autoi函数如何使用,C++的a
- 下一篇: 计算机中专专业是什么意思,计算机专业的中