1.初始化列表:在宣告時就給變數預設值 class():variable(value){};
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class a{
public:
int c,d;
a():c(100) ,d(50){};
};
---
int main(int argc, char** argv) {
a a;
cout<<a.c;//100
return 0;
}
class CExample {
public:
int a;
float b;
//构造函数初始化列表
CExample(): a(0),b(8.8)
{}
//构造函数内部赋值
CExample()
{
a=0;
b=8.8;
}
};
--
class CMyClass {
CMyClass(int x, int y);
int m_x;
int m_y;
};
CMyClass::CMyClass(int x, int y) : m_y(y), m_x(m_y)
{
}
2.explicit修飾:不讓你隱式轉換
explicit 這個修飾平常不容易看到
今天對他小研究一下
c++再轉型別轉換(type cast)的時候有為隱性(implicit)轉換跟顯性(explicit)轉換
這個其實其他語言也有,不過今天針對c++的explicit來探討
考慮下面一段程式碼
#include
using namespace std;
class Integer{
public:
int data;
Integer(int i){data=i;}
};
int main() {
Integer i=10;
cout<<i.data<<endl;
return 0;
}
像這樣一段程式碼是可以跑的
Integer i=10;
他會自動去找Integer(int i)的建構子,這樣的一個轉型行為就稱為隱式轉換
然而有時候我們會希望不准使用這種隱式轉換,這時候 explicit修飾就小兵立大功啦
將上面程式改成
#include
using namespace std;
class Integer{
public:
int data;
explicit Integer(int i){data=i;}
};
int main() {
Integer i=10;
cout<<i.data<<endl;
return 0;
}
替要防止隱式轉換的建構式將上explicit修飾,此時會編譯不過出現錯誤訊息
error: conversion from ‘int’ to non-scalar type ‘Integer’ requested
這樣用戶端就只能乖乖呼叫建構式了,將程式碼改成如下就能跑了
#include
using namespace std;
class Integer{
public:
int data;
explicit Integer(int i){data=i;}
};
int main() {
Integer i(10);//呼叫建構式
cout<<i.data<<endl;
return 0;
}
3.int a{8} 的意思是直接給值
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class a{
public:
int c{44};
};
int main(int argc, char** argv) {
a a;
cout<<a.c;
return 0;
}
8.c++的繼承
class Rectangle: public Shape {
public: int getArea() { return (width * height); } };