struct and class in C++
c++class and struct in C++ are functionally equivalent but class is private by default as opposed to struct being public. class is used for encapsulation and if it has public fields and few methods, it seems that struct is used generally.
#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
}
Both can be inherited. In C++, if you do not add virtual to make it a virtual function, the original function is called without being overridden when called from a variable of the inheritance source type.
#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?