C++学习(二)

   今天有看了下C++,对基础的内容又重新温习了一下。

2.1  类成员的访问:

     在声明类时,类的成员具有安全级别,常用的安全级别有public 、private 、protected。默认情况下,类的成员为私有的(private)。

类成员的安全级别

类的对象能否访问

能否被派生类继承

private

不能

不能

public

protected

不能

 2.2  类方法的实现:

 

  1. class CDog
  2. {
  3.     unsigned int m_Age;
  4. protected:
  5.     unsigned int m_Weight;
  6. public:
  7.     unsigned int getAge();
  8.     void setAge(unsigned int age);
  9. };
  10. unsigned int CDog::getAge()
  11. {
  12.     return m_Age;
  13. }
  14. void CDog::setAge(unsigned int age)
  15. {
  16.     if(m_Age!=age)
  17.         m_Age = age;
  18. }
  19. int main()
  20. {
  21.     CDog mydog;
  22.     mydog.setAge(10);
  23.     return 0;
  24. }

2.3  构造函数和析构函数(constructor and destructor )

       构造函数是一个与类名相同的方法,可以根据需要设置参数,但不具有返回值。如果在声明类时,没有提供构造函数,编译器会提供一个默认的构造函数,默认构造函数,不进行任何操作。构造函数可以用来动态初始化成员变量。

       析构函数与构造函数相对的,它是在对象被撤销后消除并释放所分配的内存。如果对象在栈中被创建的,那么在对象失去作用域时,系统会自动调用其析构函数来释放对象所占的内存。

  1. #include "iostream.h"
  2. class CDog
  3. {
  4. public:
  5.     unsigned int m_Age;
  6.     unsigned int m_Weight;
  7.     CDog(int weight,int age);
  8.     CDog(int weight = 20);
  9.     CDog(const CDog & theDog);    //复制构造函数-----生成一个对象的复制
  10.     unsigned int getAge();
  11.     void setAge(unsigned int age);
  12.     ~CDog();
  13. }
  14. CDog::CDog(int weight,int age)
  15. {
  16.     m_Weight = weight;
  17.     m_Age = age;
  18. }
  19. CDog::CDog(int weight)
  20. {
  21.     m_Weight = weight;
  22. }
  23. CDog::CDog(const CDog & theDog)
  24. {
  25.     m_Weight =theDog.m_Weight;
  26.     m_Age = theDog.m_Age;
  27. }
  28. unsigned int CDog::getAge()
  29. {
  30.     return m_Age;
  31. }
  32. void CDog::setAge(unsigned int age)
  33. {
  34.         m_Age = age;
  35. }
  36. CDog::~CDog()
  37. {
  38.     cout<<"did it !"<<'/t';
  39. }
  40. void test()
  41. {
  42.     CDog mydog;
  43.     CDog customdog(3,20);
  44. }
  45. int main()
  46. {
  47.     test();
  48.     return 0;
  49. }

上面的程序为什么用VC6.0编译是会出错呢?出错提示:

E:/VC++/exercise/ex6/constructor.cpp(18) : error C2533: 'CDog::CDog' : constructors not allowed a return type
E:/VC++/exercise/ex6/constructor.cpp(52) : error C2264: 'CDog::CDog' : error in function definition or declaration; function not called
执行 cl.exe 时出错.搞不明白?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值