C++ 預設建構函式
類建構函式是類的特殊成員函式,它在建立該類的物件的時候執行。
建構函式的名稱與類的名稱完全相同,但它沒有任何返回型別,甚至連 void 都沒有。建構函式對於為某些成員變數設定初始值非常有用。
下面的例子說明了建構函式的概念 −
示例
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}輸出
Object is being created Length of line : 6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP