#include <iostream>
using namespace std;
class Rectangle {
public:// 主构造函数Rectangle(int width, int height) : width_(width), height_(height) {std::cout << "Main constructor called\n";}// 委托构造函数Rectangle(int size) : Rectangle(size, size) {std::cout << "Delegating constructor called\n";}void print() const {std::cout << "Width: " << width_ << ", Height: " << height_ << "\n";}
private:int width_, height_;
};int main() {Rectangle rect(30); // 调用委托构造函数rect.print();return 0;
}
委托构造函数是 C++11 引入的特性,允许一个构造函数调用同一个类中的另一个构造函数,从而避免代码重复,提高代码的可维护性。