分析下列代码,改正其中的错误,使程序能正确运行:在成员函数的定义中显式加入this指针,程序功能仍保持不变。
#include <iostream>
using namespace std;
class TV
{
public:
void SetStation(int i);
int GetStation();
private:
int station;
};
int main()
{
TV myTV;
myTV.station=9;
myTV.SetStation(10);
TV myOtherTV(2);//创建一个对象,设置其频道数为2
}
代码块:
#include <iostream>
using namespace std;
class Time
{
public:
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
int main()
{
Time t;
t.set_time();
t.show_time();
system("pause");
return 0;
}
void Time::set_time()
{
cin>>hour>>minute>>sec;
}
void Time::show_time()
{
cout<<hour<<':'<<minute<<':'<<sec<<endl;
}
对于段落0的问题,代码如下:
#include <iostream>
using namespace std;
class Solution {
public:
int lengthOfStr(string s) {
return s.length();
}
};
int main() {
string s;
cin >> s;
Solution sol;
cout << sol.lengthOfStr(s) << endl;
return 0;
}
在类中添加了lengthOfStr函数,通过键盘输入一个字符串,返回字符串长度。
对于段落1的问题,需要找出其中的错误并改正:
代码中需要添加this指针,使得程序能够正确运行。修改后的代码如下:
//判断两个链表是否相交(假设链表可能带环)
bool CheckCrossC(pList plist1, pList plist2)
{
pNode EntryNode1 = NULL;
pNode EntryNode2 = NULL;
pNode p1 = NULL;
if (this == NULL || plist1 == NULL || plist2 == NULL)
return false;
if (CheckCycle(plist1) == NULL && CheckCycle(plist2) == NULL)
return CheckCross(plist1, plist2);
else if ((CheckCycle(plist1) != NULL && CheckCycle(plist2) == NULL) || \
(CheckCycle(plist1) == NULL && CheckCycle(plist2) != NULL))
return false;
else
{
if (GetCycleEntryNode(plist1, CheckCycle(plist1)) == GetCycleEntryNode(plist2, CheckCycle(plist2)))
return true;
else
{
EntryNode1 = GetCycleEntryNode(plist1, CheckCycle(plist1));
p1 = EntryNode1;
EntryNode2 = GetCycleEntryNode(plist2, CheckCycle(plist2));
do{
if (p1 == EntryNode2)
return true;
p1 = p1->_next;
} while (p1 != EntryNode1);
return false;
}
}
}
//求交点(假设链表可能带环)
pNode GetCrossNodeC(pList plist1, pList plist2)
{
pNode EntryNode1 = NULL;
pNode EntryNode2 = NULL;
pNode p1 = NULL;
pNode p2 = NULL;
int length1 = 1;
int length2 = 1;
int i = 0;
if (CheckCycle(plist1) == NULL && CheckCycle(plist2) == NULL)
return GetCrossNode1(plist1, plist2);
EntryNode1 = GetCycleEntryNode(plist1, CheckCycle(plist1));
EntryNode2 = GetCycleEntryNode(plist2, CheckCycle(plist2));
p1 = plist1;
p2 = plist2;
if (EntryNode1 == EntryNode2)
{
while (p1->_next != EntryNode1)
{
p1 = p1->_next;
length1++;
}
while (p2->_next != EntryNode1)
{
p2 = p2->_next;
length2++;
}
if (length1 > length2)
{
for (i = length1 - length2; i > 0; i--)
{
plist1 = plist1->_next;
}
}
else
{
for (i = length2 - length1; i > 0; i--)
{
plist2 = plist2->_next;
}
}
while (plist1 != plist2)
{
plist1 = plist1->_next;
plist2 = plist2->_next;
}
return plist1;
}
if (EntryNode1 != EntryNode2)
{
return EntryNode1;
}
}
其中,每个函数都添加了this指针,并且在判断时需要加入“this == NULL”的判断,避免程序出错。