|
--------头文件代码-----------
- class CAnimal
- {
- public:
- //char name[50]; //正常
- ////string name;
- //int score;
- //static const char* master; //
- static int master;
- char* p_name; //定义一个指针
- char sex;
- int ID;
- int num;
-
- CAnimal(); //无参数的构造函数
- CAnimal(CAnimal& stud); //拷贝构造函数
- CAnimal(const char* pname,char t_sex,int t_ID,int t_num); //有参数的重载 构造函数
- ~CAnimal(); //析构函数
- void test();
- int max_num(int x, int y);
- void set_ID();
-
- };
复制代码
--------cpp文件,函数定义代码---------
- #include "pch.h"
- #include "CAnimal.h"
- #include <iostream>
- #include <string>
- using namespace std;
- CAnimal::CAnimal()
- {
- master = 0;
- }
- CAnimal::CAnimal(const char* t_name, char t_sex, int t_ID, int t_num) :sex(t_sex), ID(t_ID), num(t_num)
- {
- p_name = NULL;
- int n_len = 0;
-
- if (t_name)
- {
- n_len = strlen(t_name);
- }
- if (n_len>0)
- {
- p_name = new char[n_len + 1]; //根据输入的字符数组分配字符数组,+1是为了成为一个字符串
- memset(p_name, 0, n_len + 1); //初始化数组
- strcpy(p_name, t_name); //copy 字符串
- }
- }
- CAnimal::CAnimal(CAnimal& stud)
- {
- }
- //可能是因为参数是用字符串指针的问题不能事业拷贝函数来执行
- //CAnimal::CAnimal(CAnimal& stud) //拷贝构造函数
- //{
- // strcpy(this->p_name, stud.p_name);
- // this->sex = stud.sex;
- // this->ID = stud.ID;
- // this->num = stud.num;
- //
- //}
- CAnimal::~CAnimal() //析构函数
- {
- if (p_name)
- {
- delete []p_name; //释放p_name空间
-
- }
- cout << "My ~CAnimal" << endl;
- }
复制代码
编译出错提示,如下图:
对不起老师,以为老师的代码肯定是没问题的,没看接下来的课程就盲目提问了。
问题已经解决:
原因是:静态变量记得这么在类外声明并初始化下
- #include "pch.h"
- #include "CAnimal.h"
- #include <iostream>
- #include <string>
- using namespace std;
- int CAnimal::master = 0;
- //静态变量是需要这样进行赋值的,否则会编译出错:无法解析的外部符号
- CAnimal::CAnimal()
- {
- //master = 0; //不能在构造函数里面对静态变量赋值
- }
复制代码
|
上一篇: MFC List control 鼠标怎么选中文字?下一篇: 在 MFC List control 单元格文字不同颜色
|