/*定义一个类Cat,包含一个私有成员变量weight,设置好weight的存取函数。
定义一个类Dog,包含一个私有成员变量weight,设置好weight的存取函数。
定义一个原型如
int getTotalWeight(const Cat &c,const Dog &d)的函数,使其成为Cat 和Dog的友元函数,用来计算一只猫和一只狗的重量和。完成两个类和函数的定义并进行测试。*/
#include <iostream>
using namespace std;
class Dog;
class Cat{
private:
int weight;
public:
Cat(int _weight);
void setWeight(int _weight);
int getWeight();
friend int getTotalWeight(const Cat &c,const Dog &d);
};
class Dog{
private:
int weight2;
public:
Dog(int _weight2);
void setWeight(int _weight2);
int getWeight();
friend int getTotalWeight(const Cat &c,const Dog &d);
};
Cat::Cat(int _weight):weight(_weight)
{
}
void Cat::setWeight(int _weight)
{
weight=_weight;
}
int Cat::getWeight()
{
return weight;
}
Dog::Dog(int _weight2):weight2(_weight2)
{
}
void Dog::setWeight(int weight2)
{
weight2=weight2;
}
int Dog::getWeight()
{
return weight2;
}
int getTotalWeight(const Cat &c,const Dog &d)
{
int w1=c.weight;
int w2=d.weight2;
return w1+w2;
}
int main()
{
Cat cat(10);
Dog dog(20);
cout<<getTotalWeight(cat,dog)<<endl;
cat.setWeight(99);
dog.setWeight(88);
cout<<getTotalWeight(cat,dog)<<endl;
return 0;
}
/*
定义一个Person类,包含一个const 型的name属性,Person带有一个无参构造函数和一个带参构造函数。
在无参构造函数中,name初始化为"无名”。设置一个读取name的函数。编码进行测试
*/
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
const string name;
public:
Person();
Person(string _name);
string getName();
};
Person::Person()
{
}
Person::Person(string _name):name(_name)
{
}
string Person::getName()
{
return name;
}
int main()
{
Person person("xlj");
cout<<person.getName()<<endl;
// person.name="xx";//因为是const类型,所以不能更改,所以测试后此句错误
// cput<<person.getName()<<endl;
return 0;
}
/*自己编码测试区分一下定义形式:
const char* p;
char * const p;
const char* const p;
*/
#include <iostream>
#include <string>
using namespace std;
/*int main()
{
char i='x';
char j='y';
const char *p=&i;
cout<<*p<<endl;
//*p='m';//经过测试,const char *p不能改变值,可以改变地址
//cout<<*p<<endl;
p=&j;
cout<<*p<<endl;
return 0;
}*/
/*int main()
{
char i='x';
char j='y';
char *const p=&i;
cout<<*p<<endl;
*p='m';
cout<<*p<<endl;
//p=&j;//经过测试,char *const p不能改变地址,可以改变值
//cout<<*p<<endl;
return 0;
}*/
int main()
{
char i='x';
char j='y';
const char *const p=&i;
cout<<*p<<endl;
// *p='m';
// cout<<*p<<endl;
// p=&j;
// cout<<*p<<endl;
//经过测试,const char *const p,不能改变地址也不能改变值,只能初始化
return 0;
}
C++(笔记)友元函数、const基础练习
最新推荐文章于 2023-09-27 22:04:03 发布