【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

     

 4.結構體和共同體:定義一個"數據類型" datatype類,能處理包含字符型、整型、浮點型三種類型的數據,給出其構造函數。

 1 #include <iostream>
 2 using namespace std;
 3  class datatype{
 4  enum{ character, integer,  floating_point } vartype;
 5  union  {  char c; int i; float f; }; 
 6  public:  datatype(char ch)
 7  { vartype = character; c = ch; } 
 8  datatype(int ii) { 
 9 vartype = integer; i = ii; } 
10 datatype(float ff) { 
11 vartype = floating_point; f = ff; } 
12 void print(); }; 
13 void datatype::print() { switch (vartype) { case character: 
14 cout << "字符型: " << c << endl; break15 case integer: 
16 cout << "整型: " << i << endl; break17 case floating_point: 
18 cout << "浮點型: " << f << endl; break; } } 
19 void main() { 
20 datatype A('c'), B(12), C(1.44F);
21 A.print(); 
22 B.print(); 
23 C.print(); 
24 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM