solving problems coping with c instead of c
play

Solving problems: coping with C instead of C++ Only pass-by-value, - PowerPoint PPT Presentation

Solving problems: coping with C instead of C++ Only pass-by-value, no reference parameters void changeIt(int * x) void changeIt(int & x) { { *x = 3; x = 3; } } int val = 13; int val = 13; changeIt(&val); changeIt(val); cout


  1. Solving problems: coping with C instead of C++ ● Only pass-by-value, no reference parameters void changeIt(int * x) void changeIt(int & x) { { *x = 3; x = 3; } } int val = 13; int val = 13; changeIt(&val); changeIt(val); cout << val << endl; cout << val << endl; ● To make an array (allocate and pass back) void fillUp(int **x) { *x = new int[100]; } int * x; what about int *x[] as param? fillUp(&x); java: addres-of operater is evil x[0] = 13; 10. 1 Duke CPS 108

  2. C++ and C-isms ● In C++ a struct is a class in which public is default ➤ supports everything a class does, including inheritance ➤ in C, a struct requires the word struct , typedef often used typedef struct node_s { int value; struct node_s * next; struct node_s * bar; } Node; Node * foo; ● pointers to functions: use right-left-right rule (watch parens) void foo(int (*df) (double,double)); typedef int (*iddfunc) (double,double); void foo(iddfunc df); 10. 2 Duke CPS 108

  3. Function objects instead of function pointers ● Problem: a function cannot maintain state that is accessible outside the function over a sequence of function calls ➤ static inside the function maintains state: not accessible ➤ global variables can be used, pollute the global namespace ➤ solution: combine state and behavior, use a class ● Function object: a class that can be used as a fucntoin ➤ overload operator() so that object can be used syntactically as a function [like a function pointer] ➤ STL supplies these as templated functions, e.g., less<int> template <class T> struct less : public binary_function<T,T,bool>{ bool operator() (const T& x, const T& y){ return x < y; } } 10. 3 Duke CPS 108

  4. When to filter entries? ● when scandir object is constructed StrFilter ccmatch(“.cc”); Scandir scanner(ccmatch); ● when DirEntry objects are loaded Scandir scanner; scanner.load(“afs/acpub/users/o/l/ola”,StrFilter(“.html”)); ● after DirEntry objects are loaded scanner.load(“/afs”); scanner.filter(ccmatch); ● when iterating Iterator<DirEntry> * iter = scanner.makeIterator(ccmatch); ● pros/cons of different methods? ● What does StrFilter look like? 10. 4 Duke CPS 108

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend