class rectangle { private: const int length; int width; int height; public: rectangle(){length=3,width-4;} //rectangle():length(3),width(5){cout<<"长方形b的面积是:" <<length*width<<endl;} };
3.2 错误现象
1
note: 'const int rectangle::length' should be initialized const int length;
3.3 说明
由于常量和引用只能被初始化,不能被赋值。因此最好在构造函数的函数头中对常量和引用进行初始化
四 示例代码及结果
4.1 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream> using namespace std; class rectangle { private: int length; int width; int height; public: // rectangle() {length = 3; width - 4;} rectangle():length(3),width(5){cout<<"长方形b的面积是:"<<length*width<<endl;}