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

时间:2025-02-22 23:37:28

【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. 使用内联示例:
     #include<iostream>
    using namespace std;
    class Dog{
    public:
    Dog(int initage=,int initweight=);
    ~Dog();
    int GetAge(){
    return age;
    }//内联隐式函数
    void setage(int ages){
    age=ages;
    }
    int getweight(){
    return weight;
    }
    void setweight(int weights){
    weight=weights;
    } private:
    int age;int weight;
    };
    Dog::Dog(int initage,int initweight){
    age=initage;
    weight=initweight;
    }
    Dog::~Dog(){
    }
    int main(){
    Dog a;
    cout<<a.getweight();
    return ;
    }

4.结构体和共同体:定义一个"数据类型" datatype类,能处理包含字符型、整型、浮点型三种类型的数据,给出其构造函数。

 #include <iostream>
using namespace std;
class datatype{
enum{ character, integer, floating_point } vartype;
union { char c; int i; float f; };
public: datatype(char ch)
{ vartype = character; c = ch; }
datatype(int ii) {
vartype = integer; i = ii; } 
datatype(float ff) { 
vartype = floating_point; f = ff; } 
void print(); }; 
void datatype::print() { switch (vartype) { case character: 
cout << "字符型: " << c << endl; break; 
case integer: 
cout << "整型: " << i << endl; break; 
case floating_point: 
cout << "浮点型: " << f << endl; break; } } 
void main() { 
datatype A('c'), B(), C(1.44F);
A.print(); 
B.print(); 
C.print(); 
}

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