0

所以我有以下 Box 类:

盒子.h

#ifndef BOX_H
#define BOX_H

class Box {

    private:
        double _length {1.0},
                _width {1.0},
                _height {1.0};

        // can be modified in const member functions
        mutable unsigned count {};

    public:
        Box() = default;
        Box(double length, double width, double height);
        Box(double side);

        Box(const Box& box);

        double volume() const;

        friend double surfaceArea(const Box& aBox);

        double& length() { return _length; }
        double& width() { return _width; }
        double& height() { return _height; }


        double length() const { return _length; }
        double width() const { return _width; }
        double height() const { return _height; }



};

#endif

盒子.cpp

#include "Box.h"
#include <iostream>

Box::Box(double length, double width, double height) : _length {length}, _width {width}, _height {height} {}
Box::Box(double side) : Box {side, side, side} {}
Box::Box(const Box& box) : Box {box.length, box.width, box.height} {}

// Function to calculate the volume of a box
double Box::volume() const {
    return this -> _length * this -> _width * this -> _height;
}

主文件

#include <iostream>
#include <memory>
#include "Box.h"

int main() {

    Box box1 {2.0, 3.0, 4.0};
    Box box2;
    auto box3 { std::make_unique<Box>(15.0, 20.0, 25.0) };

    std::cout << "Volume of box1 = " << box1.volume() << std::endl;
    std::cout << "Surface area of box1 = " << surfaceArea(box1) << std::endl;

    std::cout << "Volume of box2 = " << box2.volume() << std::endl;
    std::cout << "Surface area of box2 = " << surfaceArea(box2) << std::endl;

    std::cout << "Volume of box3 = " << box3->volume() << std::endl;
    std::cout << "Surface area of box3 = " << surfaceArea(*box3) << std::endl;

}

double surfaceArea(const Box& aBox) {
    return 2.0 * (aBox._length * aBox._width + aBox._length * aBox._height + aBox._height * aBox._width);
}

在此处输入图像描述

基于这些错误消息,我得出结论,复制构造函数的委托构造函数存在问题。所以我不确定为什么代码似乎在调用默认构造函数而不是 3-arg 构造函数。

4

1 回答 1

2

如果要调用函数,则必须添加一对括号:

Box::Box(const Box& box) : Box {box.length(), box.width(), box.height()} {}
于 2020-04-13T19:13:53.723 回答