C++中声明类的class与声明结构体的struct关键字详解
class [template-spec] class [ms-decl-spec] [tag [: base-list ]] { member-list } [declarators]; [ class ] tag declarators; 参数 使用举例 // class.cpp // compile with: /EHsc // Example of the class keyword // Exhibits polymorphism/virtual functions. #include <iostream> #include <string> #define TRUE = 1 using namespace std; class dog { public: dog() { _legs = 4; _bark = true; } void setDogSize(string dogSize) { _dogSize = dogSize; } virtual void setEars(string type) // virtual function { _earType = type; } private: string _dogSize,_earType; int _legs; bool _bark; }; class breed : public dog { public: breed( string color,string size) { _color = color; setDogSize(size); } string getColor() { return _color; } // virtual function redefined void setEars(string length,string type) { _earLength = length; _earType = type; } protected: string _color,_earLength,_earType; }; int main() { dog mongrel; breed labrador("yellow","large"); mongrel.setEars("pointy"); labrador.setEars("long","floppy"); cout << "Cody is a " << labrador.getColor() << " labrador" << endl; }
[template-spec] struct[ms-decl-spec] [tag [: base-list ]] { member-list } [declarators]; [struct] tag declarators; 参数 #include <iostream> using namespace std; struct PERSON { // Declare PERSON struct type int age; // Declare member types long ss; float weight; char name[25]; } family_member; // Define object of type PERSON struct CELL { // Declare CELL bit field unsigned short character : 8; // 00000000 ???????? unsigned short foreground : 3; // 00000??? 00000000 unsigned short intensity : 1; // 0000?000 00000000 unsigned short background : 3; // 0???0000 00000000 unsigned short blink : 1; // ?0000000 00000000 } screen[25][80]; // Array of bit fields int main() { struct PERSON sister; // C style structure declaration PERSON brother; // C++ style structure declaration sister.age = 13; // assign values to members brother.age = 7; cout << "sister.age = " << sister.age << 'n'; cout << "brother.age = " << brother.age << 'n'; CELL my_cell; my_cell.character = 1; cout << "my_cell.character = " << my_cell.character; } // Output: // sister.age = 13 // brother.age = 7 // my_cell.character = 1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |