a class use data abstraction and encapsulation defines an abstract data type.
the class designer worries about how the class is implemented. Programmers who use the class need not know how the type works. They can instead think abstractly about what the type does.
class 跟 struct 区别
class 我们没法触碰他的 data members,是通过各种 interface 来接触
而 struct 我必须去操作他的 data members,而没有 interface。如果想要把一个 struct 变为 class,就需要做一些方法让用户使用 (define operations for users to use) 一旦做出来了,就可以 encapsulate (that is, hide) its data members.
用翁恺的话来说:
class 就是有方法的 struct
在语言层面的实现上也确实是这样:struct 就是一个全为 public 的class
The only difference between using class and using struct to define a class is the default access level. (C++ Primer, p269.)
int height; // defines a name subsequently used inside Screenclass Screen { public: typedef std::string::size_type pos; void setHeight(pos); pos height = 0; // hides the declaration of height in the outer scope }; Screen::pos verify(Screen::pos); void Screen::setHeight(pos var) { // var: refers to the parameter // height: refers to the class member // verify: refers to the global function height = verify(var);}
注意看,讲道理,在class被完全定义之前,verify并未被声明,但是结果在函数体中,使用verify是合法的。这就说明了 the name is resolved in the function body’s scope, rather than the class scope.
specifying inline only on the definition outside the class can make the class easier to read.
只是改变的mem func最好也能返回obj,这样可以长串式子下去
Use Private Utility Functions for Common Code
class Screen { public: // display overloaded on whether the object is const or not Screen &display(std::ostream &os) { do_display(os); return *this; } const Screen &display(std::ostream &os) const { do_display(os); return *this; } private: // function to do the work of displaying a Screen void do_display(std::ostream &os) const { os << contents; } // other members as before };
Why bother? 总的来讲其实是防止代码重复的那些好处
terms
means
data abstraction
a technique that separate interface and implementation.
encapsulation
separate a class’ interface and implementation.
name lookup
the process of finding which declarations match the use of a name