[C++] c++ 传递引用给对象 →→→→→进入此内容的聊天室

来自 , 2021-04-05, 写在 C++, 查看 144 次.
URL http://www.code666.cn/view/e0ab531e
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class SimpleCat {
  5. public:
  6.         SimpleCat();
  7.         SimpleCat(SimpleCat&);
  8.         ~SimpleCat();
  9.  
  10.         int GetAge() const {
  11.                 return itsAge;
  12.         }
  13.         void SetAge(int age) {
  14.                 itsAge = age;
  15.         }
  16.  
  17. private:
  18.         int itsAge;
  19. };
  20.  
  21. SimpleCat::SimpleCat() {
  22.         cout << "Simple Cat Constructor..." << endl;
  23.         itsAge = 1;
  24. }
  25.  
  26. SimpleCat::SimpleCat(SimpleCat&) {
  27.         cout << "Simple Cat Copy Constructor..." << endl;
  28. }
  29.  
  30. SimpleCat::~SimpleCat() {
  31.         cout << "Simple Cat Destructor..." << endl;
  32. }
  33.  
  34. const SimpleCat & FunctionTwo(const SimpleCat & theCat);
  35.  
  36. int main() {
  37.         cout << "Making a cat..." << endl;
  38.         SimpleCat Frisky;
  39.         cout << "Frisky is " << Frisky.GetAge() << " years old" << endl;
  40.         int age = 5;
  41.         Frisky.SetAge(age);
  42.         cout << "Frisky is " << Frisky.GetAge() << " years old" << endl;
  43.         cout << "Calling FunctionTwo..." << endl;
  44.         FunctionTwo(Frisky);
  45.         cout << "Frisky is " << Frisky.GetAge() << " years old" << endl;
  46.  
  47.         return 0;
  48. }
  49.  
  50. // functionTwo, passes a ref to a const object
  51. const SimpleCat & FunctionTwo(const SimpleCat & theCat) {
  52.         cout << "Function Two. Returning..." << endl;
  53.         cout << "Frisky is now " << theCat.GetAge();
  54.         cout << " years old " << endl;
  55.         // theCat.SetAge(8); const!
  56.         return theCat;
  57. }
  58.  

回复 "c++ 传递引用给对象"

这儿你可以回复上面这条便签

captcha