C++のstructとclass
c++C++のclassとstructは同じ機能を持っているが、classのデフォルトがprivateなのに対してstructはpublicになっている。 classはカプセル化のために用いられ、公開フィールドを持ちメソッドをほとんど持たない場合はstructを使うことが多いようだ。
#include <iostream>
using namespace std;
class C {
int value;
public:
C(int value) {
this->value = value;
}
int func() {
return value;
};
};
struct S {
S(int value) {
this->value = value;
}
int value;
private:
int func() {
return value;
};
};
int main () {
C(1).value; // member "C::value" (declared at line 2) is inaccessible
C(1).func();
S(1).value;
S(1).func(); // function "S::func" (declared at line 18) is inaccessible
}
いずれも継承できる。C++では継承元の関数にvirtualを付けて仮想関数にしないと、 継承元の型の変数から呼んだ際にオーバーライドされず元の関数が呼ばれる。
#include <iostream>
using namespace std;
class c1 {
protected:
string value;
public:
c1(string value) {
this->value = value;
}
string func() {
return value;
}
virtual string vfunc() {
return value;
}
};
struct s2: public c1 {
s2(string value) : c1(value) {}
string func() {
return value + "!!";
}
string vfunc() {
return func();
}
};
int main () {
c1* c1c1 = new c1("A");
cout << c1c1->func() << endl; // => A
cout << c1c1->vfunc() << endl; // => A
delete c1c1;
c1* c1s2 = new s2("A");
cout << c1s2->func() << endl; // => A
cout << c1s2->vfunc() << endl; // => A!!
delete c1s2;
s2* s2s2 = new s2("A");
cout << s2s2->func() << endl; // => A!!
cout << s2s2->vfunc() << endl; // => A!!
delete s2s2;
}
参考
What’s the difference between the keywords struct and class?