C++(笔记)友元函数、const基础练习
2017-03-30 11:09
267 查看
/*定义一个类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; }
相关文章推荐
- Java 基础一些代码练习笔记(抽象类)
- Java 基础一些代码练习笔记(static 关键字)
- Java 基础一些代码练习笔记( TreeSet 排序)
- Java 基础一些代码练习笔记(Propertise环境变量)
- Java 基础一些代码练习笔记(策略模式)
- Java 基础一些代码练习笔记(多态1)
- Oracle基础知识笔记(11) 建表、更新、查询综合练习
- Java 基础一些代码练习笔记(HashCode重写)
- Java 基础一些代码练习笔记(队列)
- Java 基础一些代码练习笔记( GenericFoo<T> 泛型2)
- Java 基础一些代码练习笔记(static 静态代码块)
- Java 基础一些代码练习笔记(Array数组)
- Java 基础一些代码练习笔记(Integer)
- Java 基础一些代码练习笔记( Interator)
- Java 基础一些代码练习笔记(二分查找)
- Java 基础一些代码练习笔记(继承+接口+多态)
- Java 基础一些代码练习笔记(StringBuffer)
- Java 基础一些代码练习笔记(ArrayEquals)
- Java 基础一些代码练习笔记(HashMap)
- C++基础学习笔记----第六课(const和引用的扩展、重载函数和C方式编译的深入)