首页 > 应用开发 > > C++初学者关于创建类中的疑问
我用VS2012学习C++,发现在自己编写类的过程中经常遇到无法找到错误的错误,最常见的就是外部解析无效,总是无法通过编译。
例如编写一个Date类
代码附上:
Date.h头文件
1 #ifndef DATE_H
2 #define DATE_H
3
4 class Date
5 {
6 public:
7
8 Date(int=2018,int=1,int=1);
9 ~Date(void);
10 void displayDate()const;
11 bool setYear(int Year);
12 int getYear()const;
13 bool setMonth(int Month);
14 int getMonth()const;
15 bool setDay(int Day);
16 int getDay()const;
17 operator char*()const;
18 char *showStr();
19 private:
20 int Month;
21 int Day;
22 int Year;
23 char *str;
24 void operator=(char *); //拒绝赋值
25 Date(const Date&); //拒绝拷贝
26
27 };
28
29 #endif
Date.cpp定义文件
1 #include "Date.h"
2 #include <iostream>
3 #include <cstring>
4 using std::string;
5
6 Date::~Date(void)
7 {
8 delete[]str;
9 }
10 Date::operator char *()const
11 {
12 /*itoa(Year,&str[0],10);
13 itoa(Month,&str[5],10);
14 itoa(Day,&str[8],10);
15 str[strlen(str)]='\0';
16 //return "2011/11/11Defined!";*/
17 return str;
18 }
19 char *Date::showStr() {return str;}
20
21 Date::Date(int year,int month, int day):str(new char[20])
22 {
23 setYear(year);
24 setDay(day);
25 setMonth(month);
26 strcpy(str,"helloworld");
27 }
28
29 void Date::displayDate() const
30 {
31 std::cout << getYear() <<"/" <<getMonth() <<"/" << getDay() ;
32
33 }
34
35 bool Date::setYear(int year)
36 {
37 if (year>=1899 && year <=2099)
38 { Year=year;
39 return true;
40 }
41 else
42 return false;
43
44 }
45
46 int Date::getYear() const
47 {
48 return Year;
49 }
50
51 bool Date::setMonth(int month)
52 {
53 if (month >=1 && month <=12)
54 {
55 Month =month;
56 return true;
57 }
58 else
59 return false;
60 }
61
62
63 int Date::getMonth()const
64 {
65 return Month;
66 }
67
68
69 bool Date::setDay(int day)
70 {
71 if (day >=1 && day <=31)
72 {
73 Day =day;
74 return true;
75 }
76 else
77 return false;
78 }
79
80 int Date::getDay()const
81 {
82 return Day;
83 }
驱动文件main.cpp:
复制代码
1 #include "D:\数据资料区\投票系统\C++\MyFirstClass\MyFirstClass\Date.h"
2 #include <iostream>
3 using std::cout;
4 using std::cin;
5 using std::endl;
6
7 int main()
8 {
9 bool flag=true;
10 int intNum=0;
11
12 Date mydate;
13 //mydate.displayDate();
14
15 cout<<"Now Try << to dispaly Date:"<<endl;
16 cout << mydate <<endl;
17 cout<<"show string:"<< mydate.showStr()<<endl;
18 system("pause");
19 return 0;
20 }
复制代码
完整的代码就是这样,然而问题就来了。
错误 2 error LNK1120: 1 个无法解析的外部命令 D:\数据资料区\投票系统\C++\myUseDate\Debug\myUseDate.exe 1 1 myUseDate
错误 1 error LNK2019: 无法解析的外部符号 "public: char * __thiscall Date::showStr(void)" (?showStr@Date@@QAEPADXZ),该符号在函数 _main 中被引用 D:\数据资料区\投票系统\C++\myUseDate\myUseDate\main.obj myUseDate
问题就集中在showStr()函数上了,到底哪里出问题了呢?
请各位大神指教!!!来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4547/viewspace-3149001/ ,如需转载,请注明出处,否则将追究法律责任。