//【4.18】指出下面程序中的错误,并说明原因
#include <iostream>
using namespace std;
class CTest{
public:
CTest()
{ x=20; }
void use_friend();
private:
int x;
friend void friend_f(CTest fri);
};
void friend_f(CTest fri)
{
fri.x=55;
}
void CTest::use_friend()
{
CTest fri;
this->friend_f(fri); //错误,友元函数不是成员函数
::friend_f(fri); //所以不能用this->调用友元函数
}
int main()
{
CTest fri,fril;
fri.friend_f(fri); //错误,友元函数不是成员函数
friend_f(fril); //所以不能用“对象.函数名”调用友元函数
return 0;
}
//【4.19】指出下面程序中的错误,并说明原因
#include <iostream>
using namespace std;
class CTest{
public:
CTest()
{ x=20; }
void use_this();
private:
int x;
};
void CTest::use_this()
{
CTest y,*pointer;
this=&y; //错误!!不能对this直接赋值,this指针不可修改,因为它只指向自己的对象,是个常指针
*this.x=10; //错误!!按优先级原句的含义是*(this.x),显然不对
pointer=this; //正确的写法是(*this).x=10;或this->x=10;
pointer=&y;
} //因为它只指向自己的对象,是个常指针
int main()
{
CTest y;
this->x=235; //错误,this的引用不能在外部函数中,只能在内部函数中 。而且x是私有数据成员,不可直接访问
return 0;
}
//【4.20】写出下面程序的运行结果
#include <iostream>
using namespace std;
class toy{
public:
toy(int q,int p)
{
quantity=q;
price=p;
}
int get_quantity()
{
return quantity;
}
int get_price()
{
return price;
}
private:
int quantity,price;
};
int main()
{
toy op[3] [2]={
toy(10,20),toy(30,48),
toy(50,68),toy(70,80),
toy(90,16),toy(11,120),
};
for(int i=0;i<3;i++)
{
cout<<op[i] [0].get_quantity()<<",";
cout<<op[i] [0].get_price()<<"\n";
cout<<op[i] [1].get_quantity()<<",";
cout<<op[i] [1].get_price()<<"\n";
}
}
//【4.21】写出下面程序的运行结果
#include <iostream>
using namespace std;
class example{
public:
example(int n)
{
i=n;
cout<<"Constructing\n";
}
~example()
{
cout<<"Destructing\n";
}
int get_i()
{
return i;
}
private:
int i;
};
int sqr_it(example o)
{
return o.get_i()*o.get_i(); //形参对象o在函数结束时,其生命周期结束,调用析构函数
}
int main()
{
example x(10);
cout<<x.get_i()<<endl;
cout<<sqr_it(x)<<endl;
return 0; //形参对象x在函数结束时,其生命周期结束,调用析构函数
}
//【4.22】写出下面程序的运行结果
#include <iostream>
using namespace std;
class aClass{
public:
aClass()
{ total++; }
~aClass()
{ total--; }
int gettotal()
{return total;}
private:
static int total;
};
int aClass::total=0;
int main()
{
aClass o1,o2,o3;
cout<<o1.gettotal()<<" objects in existence\n";
aClass *p;
p=new aClass;
if(!p){
cout<<"Allocation error\n";
return 1;
}
cout<<o1.gettotal();
cout<<" objects in existence after allocation\n";
delete p;
cout<<o1.gettotal();
cout<<" objects in existence after deletion\n";
return 0;
}
?
//【4.23】写出下面程序的运行结果
#include <iostream>
using namespace std;
class test{
public:
test();
~test(){};
private:
int i;
};
test::test()
{
i=25;
cout<<"Here's the program output. \n";
cout<<"Let's generate some stuff... \n";
for(int ctr=0;ctr<10;ctr++)
{
cout<<"Counting at "<<ctr<<"\n";
}
}
test anObject;
int main()
{
return 0;
}
?