boat car
weight weight
友元函数:getTotalWeight
前向引用声明
#include<iostream>
using namespace std;
class Boat;//前向引用
class Car;//前向引用
class Boat {
public:
Boat(float w);
private:
float weight;
};
Boat::Boat(float w){
weight = w;
}
class Car {
public:
Car(float w);
friend float getTotalWeight(Boat&b,Car&c);
private:
float weight;
};
Car::Car(float w) {
weight = w;
}
float getTotalWeught(Boat&b,Car&c) {
float total=b.weight+c.weight
}
常类型
必须被初始化,且不能更新
常引用
const 类型说明符&引用名
常对象
类名 const 对象名
const可以拿了前面
const 类名 对象名
#include<iostream>
using namespace std;
void display(const double& r);
int main()
{ double d(9.5);
display(d);
return 0;
}
void display(const double& r)
//常引用做形参,在函数中不能更新 r所引用的对象。
{
r+1;//这里出警告,不能改变r的值。
cout<<r<<endl; }
----------------------------
class A
{
public:
A(int i,int j) {x=i; y=j;}
...
private:
int x,y;
};
A const a(3,4); //a是常对象,不能被更新
-----------------------------
#include<iostream>
using namespace std;
class R
{ public:
R(int r1, int r2){R1=r1;R2=r2;}
void print();
void print() const;//常函数
private:
int R1,R2;
};
void R::print()
{ cout<<R1<<":"<<R2<<endl;
}
void R::print() const
{ cout<<R1<<";"<<R2<<endl;
}
void main()
{ R a(5,4);
a.print(); //调用void print()
const R b(20,52);
b.print(); //调用void print() const
}
常数组
类型说明符 const 数组名【大小】
常指针
常函数
类型说明符 函数名(参数表)const
const关键字可以用于重载函数的区分
#include<iostream>
using namespace std;
class R {
public:
R(int r1,int r2):r1(r1),r2(r2){}//类的组合?
//R(int x1,int x2):r1(x1),r2(x2){}直接实现了,没有声明。
//可以用于初始化x1为参数,r1为内嵌对象
void print() const;//声明常函数
private:
int r1,r2;
};
void R::print() {
cout << "r1=" << r1 << "r2=" << r2 << endl;
}
void R::print() const {
cout << "const r1=" << r1 << "r2=" << r2 << endl;
}
int main() {
R a(5, 4);
a.print();
R const b(20, 52);//常对象
b.print();
return 0;
}
常对象访问只能访问常函数,不能访问其他函数,普通对象访问常函数只有在不重载的情况下,常对象和非常对象都可以访问常函数。
对比上面类的组合
//类的组合
class Line{
public:
Line(Point xp1,Point xp2);
Line(Line &q);
double getLen(){return len;}
private:
Point p1,p2;
double len;
};
//组合类的构造函数
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}