默认参数
函数重载和默认参数函数会达到同样的效果默认参数写起来简单, 理解起来难
默认构造参数有个缺点是, 当参数不断增加的时候, 理解起来会有点困难
- #include <QCoreApplication>
- #include <iostream>
- class Rectangle
- {
- public:
- Rectangle(int aWidth, int aHeight);
- ~Rectangle() {}
- void drawShape(int aWidth, int aHeight, bool useCurrentValue = false) const;
- private:
- int width;
- int height;
- };
- Rectangle::Rectangle(int aWidth, int aHeight)
- {
- width = aWidth;
- height = aHeight;
- }
- void Rectangle::drawShape(int aWidth, int aHeight, bool useCurrentValue) const
- {
- int printWidth;
- int printHeight;
- if (useCurrentValue == false)
- {
- printHeight = aHeight;
- printWidth = aWidth;
- }
- else
- {
- printHeight = height;
- printWidth = width;
- }
- for(int i = 0; i < printHeight; i++)
- {
- for(int j = 0; j < printWidth; j++)
- std::cout << *;
- std::cout << std::endl;
- }
- }
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- Rectangle box(10, 2);
- box.drawShape(5, 5);
- box.drawShape(5, 5, true);
- return a.exec();
- }
构造函数重载: 构造函数的创建分为两个阶段
初始化阶段
函数体阶段
- Tricycle::Tricycle() :
- speed(5),
- wheelSize(12)
- {
- //other statements
- }
构造函数后面的冒号表示要开始初始化了, 函数体完成其他的赋值操作
常量变量和引用必须在初始化的时候给定值, 所以类内的引用 const 等必须用这种技术
Copy Constructor
编译器会自动创建复制构造函数, 每次发生复制时候调用
当向一个类中传值的时候, 就会调用复制构造函数创建一个临时复制的对象
复制构造函数只接受一个参数指向同一类对象的引用, 由于复制不会改变传入的对象, 所以最好定义为 const 类型的, 例如
Tricycle(const Tricycle &trike);
来源: http://www.bubuko.com/infodetail-2533592.html