今天有看了下C++,对基础的内容又重新温习了一下。
2.1 类成员的访问:
在声明类时,类的成员具有安全级别,常用的安全级别有public 、private 、protected。默认情况下,类的成员为私有的(private)。
类成员的安全级别 |
类的对象能否访问 |
能否被派生类继承 |
private |
不能 |
不能 |
public |
能 |
能 |
protected |
不能 |
能 |
2.2 类方法的实现:
- class CDog
- {
- unsigned int m_Age;
- protected:
- unsigned int m_Weight;
- public:
- unsigned int getAge();
- void setAge(unsigned int age);
- };
- unsigned int CDog::getAge()
- {
- return m_Age;
- }
- void CDog::setAge(unsigned int age)
- {
- if(m_Age!=age)
- m_Age = age;
- }
- int main()
- {
- CDog mydog;
- mydog.setAge(10);
- return 0;
- }
2.3 构造函数和析构函数(constructor and destructor )
构造函数是一个与类名相同的方法,可以根据需要设置参数,但不具有返回值。如果在声明类时,没有提供构造函数,编译器会提供一个默认的构造函数,默认构造函数,不进行任何操作。构造函数可以用来动态初始化成员变量。
析构函数与构造函数相对的,它是在对象被撤销后消除并释放所分配的内存。如果对象在栈中被创建的,那么在对象失去作用域时,系统会自动调用其析构函数来释放对象所占的内存。
- #include "iostream.h"
- class CDog
- {
- public:
- unsigned int m_Age;
- unsigned int m_Weight;
- CDog(int weight,int age);
- CDog(int weight = 20);
- CDog(const CDog & theDog); //复制构造函数-----生成一个对象的复制
- unsigned int getAge();
- void setAge(unsigned int age);
- ~CDog();
- }
- CDog::CDog(int weight,int age)
- {
- m_Weight = weight;
- m_Age = age;
- }
- CDog::CDog(int weight)
- {
- m_Weight = weight;
- }
- CDog::CDog(const CDog & theDog)
- {
- m_Weight =theDog.m_Weight;
- m_Age = theDog.m_Age;
- }
- unsigned int CDog::getAge()
- {
- return m_Age;
- }
- void CDog::setAge(unsigned int age)
- {
- m_Age = age;
- }
- CDog::~CDog()
- {
- cout<<"did it !"<<'/t';
- }
- void test()
- {
- CDog mydog;
- CDog customdog(3,20);
- }
- int main()
- {
- test();
- return 0;
- }
上面的程序为什么用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 时出错.搞不明白?