const reference : const parameters « Function « C++ Tutorial






#include <iostream>
 
 class MyType
 {
 public:
     MyType();
     MyType(int initialValue);
     ~MyType(){}
     int GetItsVal()const { return itsVal; }
     void SetItsVal(int x) {itsVal = x; }
     MyType Add(const MyType &);
 
 private:
     int itsVal;
 
 };
 
 MyType::MyType(int initialValue): itsVal(initialValue) {}
 
 MyType::MyType(): itsVal(0) {}
 
 MyType MyType::Add(const MyType & rhs)
 {
     return MyType(itsVal+ rhs.GetItsVal());
 }
 
 int main()
 {
     MyType varOne(2), varTwo(4), varThree;
     varThree = varOne.Add(varTwo);
     std::cout << "varOne: " << varOne.GetItsVal()<< std::endl;
     std::cout << "varTwo: " << varTwo.GetItsVal() << std::endl;
     std::cout << "varThree: " << varThree.GetItsVal() 
         << std::endl;
     return 0;
 }
varOne: 2
varTwo: 4
varThree: 6








7.7.const parameters
7.7.1.Use a const pointer parameter
7.7.2.const reference