zoukankan      html  css  js  c++  java
  • C++中class设置思路模板

     1 #define _CRT_SECURE_ND_WARNINGS
     2 #include<iostream>
     3 #include<string>
     4 using namespace std;
     5 
     6 class Person
     7 {
     8 public:
     9     //设置年龄
    10     void setAge(int age)
    11     {
    12         if (age <0 || age > 100)
    13         {
    14             cout << "你这个老妖精" << endl;
    15             return;
    16         }
    17         m_Age = age;
    18     }
    19     //获取年龄
    20     int getAge()
    21     {
    22         return m_Age;
    23     }
    24 
    25     string getName()
    26     {
    27         return m_Name;
    28     }
    29     //写姓名
    30     void setName(string name)
    31     {
    32         m_Name = name;
    33     }
    34     //写情人
    35     void setLover(string lover)
    36     {
    37         m_lover = lover;
    38     }
    39 
    40 private: //类外不可以访问,类内可以访问
    41     int m_Age = 0; //年龄 读写
    42     string m_Name; //姓名 读写
    43     string m_lover; //情人 只写
    44 };
    45 
    46 void test01()
    47 {
    48     Person p1;
    49     p1.setName("老王");
    50     
    51     cout << "p1的姓名:" << p1.getName() << endl;
    52 
    53     p1.setAge(50);
    54 
    55     cout << "p1的年龄:" << p1.getAge() << endl;
    56 
    57     //只能设置,外部不能访问
    58     p1.setLover("常老师");
    59 
    60 }
    61 int main() {
    62     test01();
    63     system("pause");
    64     return EXIT_SUCCESS;
    65 }

     建议将所有成员属性设置为私有,自己提供对外接口来进行set或者get方法

  • 相关阅读:
    暑假学习
    暑假学习
    暑假学习
    暑假学习
    暑假学习
    经验教训+总结
    NT 时刻
    联赛模拟测试 17
    联赛模拟测试 16
    联赛模拟测试 15
  • 原文地址:https://www.cnblogs.com/gfgwxw/p/10608548.html
Copyright © 2011-2022 走看看