【C++/类与对象总结】

 

 1.以上是对本章知识的大致梳理,下面通过我自己在编程中遇到的问题再次总结。

  1. 私有成员必须通过get()函数访问吗?能不能直接调用?
    • 私有成员必须通过公共函数接口去访问,比如设置set()修改成员内容,利用get()取值。
    • 另外还可以利用友元访问#include<iostream>
      using namespace std;

      class B;
      class A
      {
      friend B;
      public:
      A(){}
      ~A(){}
      private:
      void print(){cout << "It's in A class" << endl;}
      };

      class B
      {
      public:
      B(){}
      ~B(){}
      void test(){a.print();}//A的私有成员函数直接调用
      private:
      A a;
      };

      int main()
      {
      B b;
      b.test();
      system("pause");
      return 0;
      }
  2. 构造函数()要不要写出参数?
    1. 在类中构造函数必须要有形参,可以给定默认值参数,也可以不给。对象初始化可以通过对象.(参数),也可以通过对象.set()修改默认值。
  3. 使用内联示例:
     1 #include<iostream>
     2 using namespace std;
     3 class Dog{
     4     public:
     5         Dog(int initage=0,int initweight=0);
     6         ~Dog();
     7         int GetAge(){
     8             return age;
     9         }//内联隐式函数 
    10         void setage(int ages){
    11             age=ages;
    12         }  
    13         int getweight(){
    14             return weight;
    15         }
    16         void setweight(int weights){
    17             weight=weights;
    18         }
    19         
    20     private:
    21         int age;int weight;
    22 }; 
    23     Dog::Dog(int initage,int initweight){
    24         age=initage; 
    25         weight=initweight;
    26     }
    27     Dog::~Dog(){
    28     }
    29     int main(){
    30         Dog a;
    31         cout<<a.getweight();
    32         return 0;
    33     }
    View Code

相关文章:

  • 2021-09-23
  • 2021-04-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
  • 2022-01-14
猜你喜欢
  • 2022-01-16
  • 2021-04-08
  • 2022-12-23
  • 2021-06-28
  • 2021-11-18
  • 2022-02-02
  • 2021-07-11
相关资源
相似解决方案