聚合结构构造函数



我有以下代码:

#include <iostream>
using namespace std;
struct Point {
    double x,y;
    Point(double x=0, double y=0): x(x), y(y) {}
};
struct Triangle {
    Point A,B,C;
    Triangle(Point A=Point(), Point B=Point(), Point C=Point()): A(A), B(B), C(C) {}
    void output()
    {
        cout<<"A: "<<A.x<<";"<<A.y<<endl;
        cout<<"B: "<<B.x<<";"<<B.y<<endl;
        cout<<"C: "<<C.x<<";"<<C.y<<endl;
    }
};
int main() {
    Triangle t;
    t.output();
    return 0;
}

一切正常。我的问题是关于具有默认参数的Triangle构造函数。这是通过像这样调用Point构造函数来初始化成员的正确方法Point A=Point()(在效率和干净代码方面(?

在代码清洁度方面,我更愿意提供两个构造函数:

Triangle(Point inA, Point inB, Point inC): A(inA), B(inB), C(inC) {}
Triangle() : Triangle(Point(), Point(), Point()) {}

这是通过调用 Point 构造函数来初始化成员的正确方法吗 点 A=Point(((就效率和干净的代码而言(?

这是正确的。

你不能只用一种方法来谈论效率。您需要提出第二种方法,然后比较它们的效率。

就清洁度而言,我认为最好使用与成员变量不同的函数参数名称。

编译器将在您使用时创建正确的代码

Triangle(Point A=Point(), Point B=Point(), Point C=Point()): A(A), B(B), C(C) {}

但它使用起来更人性化

Triangle(Point inA = Point(), Point inB = Point(), Point inC = Point()): A(inA), B(inB), C(inC) {}

相关内容

最新更新