コンストラクタ関数もオーバーロードできる
- 柔軟性を得る
- 配列のサポート
- コピーコンストラクタを作成すること
study145.cpp
#include <iostream>
using namespace std;
class myclass {
int x;
public:
myclass() {
x = 0;
}
myclass( int n ) {
x = n;
}
int getx() {
return x;
}
};
int main() {
myclass o1(10);
myclass o2;
cout << "o1: " << o1.getx() << "\n";
cout << "o2: " << o2.getx() << "\n";
return 0;
}
$ ./study145
o1: 10
o2: 0
stdudy149.cpp
#include <iostream>
using namespace std;
class myclass {
int x;
public:
myclass() {
x = 0;
}
myclass( int n ) {
x = n;
}
int getx() {
return x;
}
void setx( int n ) {
x = n;
}
};
int main() {
myclass *p;
myclass ob(10);
p = new myclass[10];
if( !p ) {
cout << "メモリ割り当てエラー\n";
return 1;
}
for ( int i = 0; i < 10; ++i ) {
p[i] = ob;
}
for ( int i = 0; i < 10; ++i ) {
cout << "p[" << i << "]: " << p[i].getx();
cout << "\n";
}
return 0;
}
$ ./study149
p[0]: 10
p[1]: 10
p[2]: 10
p[3]: 10
p[4]: 10
p[5]: 10
p[6]: 10
p[7]: 10
p[8]: 10
p[9]: 10
引用・参考はこちら
独習C++ 第4版
https://www.amazon.co.jp/dp/4798119768