Although I am a programmer for a long time, I am still a beginner in C++. Sometimes, I saw the argument of a method of class will pass an class object by const reference. I try to figure it out how it works and why to use it. The following is one example from a forum discussion, which clearly explain my question:

Note the following is partly cited from http://www.daniweb.com/software-development/cpp/threads/159715

Let us start with machine.

It has a method increment, Let us say that add a value to to rackID.
That doesn't need to take ANOTHER machine object.

Then we are going to write a method add that takes another machine object and adds their rackIDs together.
[I could use operator+ BUT that adds a complication so I am not. I use a reference because (a) a copy would be expensive (b) you have not provided a copy constructor and that can lead to problems, and you have a string object, so it will.]

Note in add, we add TWO Machine objects and the SECOND object does not change. I reference the second object without changing it. Since A is also an object then you can access A's private members. This would not be the case for saying 
void Machine::Test(const Other& X) .

For the first Machine objects we defined, it has a default pointer: this. 

Here is the class definition:


#include<iostream>
#include
<string>
 
using namespace std;
 
class Machine
{
 
public:
 
    
string owner;
    
string make;
    
int rackID;
 
    Machine() : rackID(
0) {}
    
virtual ~Machine() {}
    
virtual void displayMachineDetails();
    
void increment(const int =1);
    
void add(const Machine&);
};
 
void Machine::displayMachineDetails()
{
    cout 
<<"\nMachine owner: " << owner << "\nMake:         " << make
                              
<< "\nRack ID:      " << rackID << endl;
}
 
void Machine::increment(const int Index)
{
   rackID
+=Index;
}
 
void Machine::add(const Machine& A)
{
   rackID
+=A.rackID;
   
return;
}
                                                     
 
int main()
{
  Machine a 
= Machine("Me""IBM"1);
  a.increment(
111);
}
 
Posted on 2011-08-05 08:22 于江浩 阅读(196) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理