1. 构造函数中的初始化有两种方式,一种是针对参数的直接设置默认值,如(constructor(int num = 1, int sum = 0)),另一种则是在函数原型之后附加上初始化列表,针对参数、成员数据进行初始化,值得一提的是,对于const/static成员、没有默认构造函数的类对象成员都需要使用第二种方式进行初始化。
2. Mutalbe和Const。有些时候我们希望变量在程序运行过程中保持不变,会为其设置const属性;但是此时如果传入参数的过程修改参数的数据就会引发错误,因此我们可以将函数过程也声明为const(常函数),如(int length() const {return _length;}),编译器就会检查常函数是否修改了类对象的数值。但是还有些时候我们认为类对象中的某些属性与对象核心属性无关,可以改变,就将其声明为mutable类型,则const函数也可以改变其值。应该说C++的const/mutalbe提供了非常大的灵活性。更详细和深入的内容留待以后实际用到时才补充。
3. Static成员。对于类中的static成员属于类中所有对象所共有的,因此每个类中只有一份,没有副本。静态成员函数的主要目的是使得与类成员数据无关的操作函数可以独立于类对象而直接调用,如class::function而非object.function。
最后,学习编程不敲代码果然不行,哪怕比着书上的例子敲呢!这里附上一个关于栈的类,可以看到关于类的基本的语法点。
点击(此处)折叠或打开
- #include <cstdlib>
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- //Class Stack Define
- class Stack
- {
- //类中声明成员函数,可以给出简单函数的定义,默认作为inline使用,如这里的size()
- public:
- bool push( string &);
- bool pop(string &elem);
- bool peek(string &elem);
- bool empty();
- bool full();
-
- int size() {return _stack.size();}
- private:
- vector<string> _stack;
- };
- //Initial Stack
- //EOF is ctrl + D
- //本例充分使用了vector的泛型算法
- void fill_stack(Stack &stack, istream &is = cin)
- {
- string str;
- while (is >> str && !stack.full())
- stack.push(str);
- cout << "Read in "<< stack.size()<< " elements\n";
- }
-
- bool Stack::push(string &elem)
- {
- if (full())
- return false;
- _stack.push_back(elem);
- return true;
- }
- inline bool
- Stack::empty()
- {
- return _stack.empty();
- }
- bool
- Stack::pop(string &elem)
- {
- if (empty())
- return false;
- elem = _stack.back();
- _stack.pop_back();
- return true;
- }
- inline bool
- Stack::full()
- {
- return _stack.size() == _stack.max_size();
- }
- //peek() is used to check the last elem in Stack
- bool Stack::peek(string &elem)
- {
- if (empty())
- return false;
- elem = _stack.back();
- return true;
- }
- int main(int argc, char *argv[])
- {
- cout <<"A Stack Test...\n";
-
- string elem;
- string &r_elem = elem;
-
- Stack stack;
- fill_stack(stack);
- stack.peek(r_elem);
- cout << "the last elem is : "<< r_elem<<endl;
-
- system("PAUSE");
- return EXIT_SUCCESS;
- }