⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 5memberi.html

📁 C ++ in action
💻 HTML
字号:
<html>
<head>
    <title>Member Functions</title>
    <meta  name="description" content="Member functions in C++">
    <meta name="keywords" content="class, member, function, method, interface, return, void">
    <link rel="stylesheet" href="../../rs.css">
</head>

<body background="../../images/margin.gif" bgcolor="#FFFFDC">

<!-- Main Table -->
<table cellpadding="6">
    <tr>
    <td width="78">
	&nbsp;
    <td>
<h3>Member functions and Interfaces</h3>

<p class=topics>
Input stream, member functions (methods), return values, interfaces, functions returning void.
<p>
So far we have been constructing and destroying objects. What else can we do to an object? We can't access its private data members, because the compiler wouldn't let us (not to mention that I haven't even talked about the syntax one would use to do it). It turns out that only the object itself (as specified in its class definition) can make a decision to expose some of its behavior and/or contents. Behavior is exposed via member functions, also called methods. If a member function is public, anybody can call it (we'll see the syntax in a moment). 
<p>
Our first member function is called <var>GetValue</var>. It returns an <var>int</var>. From the implementation of this function we can see that the returned value is that of the private data member <var>_num</var>. 
Now we know what it means to have access to an object; it means to be able to invoke its member functions. Here, the object <var>num</var> of the type <var>InputNum</var> is defined in the scope of main and that's where we can access it. And access we do, calling <var>num.GetValue()</var>. To put it in different words, we invoke the method GetValue() on the object num. Or, we are getting the value of object <var>num</var>. In still other words (Smalltalk-speak) we send the message <var>GetValue</var> to the object <var>num</var>. What we are getting back is an <var>int</var>, which we print immediately using our old friend <var>std::cout</var>.

<tr>
<td class=margin valign=top width="78">
Download the <b>Input</b> series of sources
<br>
<a href="source/Input.zip">
<img src="../../images/brace.gif" width=16 height=16 border=1 alt="Download!"><br>source</a>
<td>

<!-- Code -->
<table width="100%" cellspacing=10><tr>
    <td class=codeTable>
<pre>#include &lt;iostream&gt;

class  <span class=method>InputNum</span>
{
public:
    InputNum ()
    {
        std::cout &lt;&lt; "Enter number ";
        std::cin &gt;&gt; _num;
    }

    int GetValue () const {  return _num; }
private:
    int _num;
};

int main()
{
    InputNum num;
    std::cout &lt;&lt; "The value is " &lt;&lt; num.GetValue() &lt;&lt; "\n";
    return 0;
}
</pre>
</table>
<!-- End Code -->

<p>
A few words of syntax clarification are in order. The type of the return value is always specified in front of the member function definition (or declaration, as will be explained later). A method that is supposed to return something must have a return statement at the end (later we'll see that a return from the middle is possible, too). If a function is not supposed to return anything, its return type is <var>void</var>. In all our previous examples <var>main</var> wasn't returning anything, so it was declared <var>void</var>. 
<p>
Not this time though. It turns out that <var>main</var> can return an integer. In fact it always returns an integer, even if it is defined as returning <var>void</var> (in that case it returns a more or less random number). By convention, <var>main</var> is supposed to return 0 if the program was successful. Otherwise it is supposed to return an error level. You can check for the error level after you've run your program from a batch file using the statement similar to this:
<!-- Code -->
<table width="100%" cellspacing=10><tr>
    <td class=codeTable>
<pre>if not errorlevel 1 goto end</pre>
</table>
<!-- End Code -->

<p>
The keyword <var>const</var> following the declaration of a method, as in
<!-- Code -->
<table width="100%" cellspacing=10><tr>
    <td class=codeTable>
<pre>int GetValue () const</pre>
</table>
<!-- End Code -->

means that this method does not change the state of the object. The compiler will not allow such a method to perform assignment, increment, or decrement of any data member, nor will it permit this method to call any non-constant methods of that class. 
<p>
Moreover, only methods declared <var>const</var> may be called on a <var>const</var> object. So far we've seen a <var>const</var> object <var>_matter</var> inside <var>World</var>. If <var>Matter</var> had a <var>const</var> method, like <var>GetValue</var>, it would have been okay to call it in the context of the object <var>_matter</var> (that is: <var>_matter.GetValue()</var> would compile all right). We'll see examples of that later. 
<p>
By the way, <var>_num</var> cannot be declared <var>const</var> any more, since it is not initialized in the preamble. The code in the body of the constructor is changing the (undefined) value of <var>_num</var>. Try compiling this program with a <var>const _num</var> and you'll see what happens.
<p>
When the object <var>num</var> of class <var>InputNum</var> is constructed in <var>main</var>, it prompts the user to input a number. It then waits for a number and stores it in its private data member <var>_num</var>. This is done through the services of the input object <var>std::cin</var>. <var>Std::cin</var> gets input from the keyboard and stores it in a variable. Depending on the type of the variable, <var>std::cin</var> expects different things from the keyboard. For instance, if you call it with an <var>int</var>, it expects an integer; if you call it with a <var>double</var>, it expects a floating point number, etc. 
<p>
The set of  public methods is called the <i>interface</i> and it defines the way clients may interact with the object. <var>InputNum</var>, for instance, provides read-only access to its contents. Because of that, we are guaranteed that the value of <var>InputNum</var> will never change once it is created. Successive calls to <var>GetValue()</var> will always return the same value.
<p>
If it makes sense, it is also possible for an object to grant write access to its contents--for example, in our case, by defining the method
<!-- Code -->
<table width="100%" cellspacing=10><tr>
    <td class=codeTable>
<pre>void SetValue (int i) { _num = i; }</pre>
</table>
<!-- End Code -->

<p>
Then, after the call
<!-- Code -->
<table width="100%" cellspacing=10><tr>
    <td class=codeTable>
<pre>num.SetValue (10);</pre>
</table>
<!-- End Code -->

subsequent calls to <var>GetValue</var> would return 10, no matter what number was input in the constructor of <var>num</var>. By the way, the equal sign in C++ signifies assignment (same as <var>:=</var> in Pascal). The statement
<!-- Code -->
<table width="100%" cellspacing=10><tr>
    <td class=codeTable>
<pre>_num = i;</pre>
</table>
<!-- End Code -->

sets the value of <var>_num</var> to that of <var>i</var>. Of course the method <var>SetValue</var> cannot be defined <var>const</var>, because it changes the state of the object (try it!). And if <var>Matter</var> had such a non-constant method, that method couldn't have been called in the context of the constant object <var>_matter</var> inside the <var>World</var>. The compiler would have strongly objected.
<p class=summary>
To summarize, the set of public member functions defines the interface to the object of a given class. What is even more important, a well designed and well implemented object is able to fulfill a well defined contract. Programming in C++ is about writing contracts and fulfilling them. An interface can, and should, be designed in such a way that the client's part of the contract is simple and well defined. The object may even be able to protect itself from sloppy clients who break their part of the contract. We'll talk about it when we discuss the use of assertions.


</table>
<!-- End Main Table -->
</body>
</html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -