C++ 类复制构造函数初始化

C++ class copy constructor initialization

提问人:Jason 提问时间:7/7/2022 最后编辑:Remy LebeauJason 更新时间:7/7/2022 访问量:105

问:

我是 C++ 的新手,我对为什么可以在第 70 行将复制构造函数初始化为 .但是实现是 ,那么为什么会等价于 ?const Animal c = b;Animal::Animal(const Animal & a)Animal c = bAnimal c (b)

代码如下:

#include <cstdio>
#include <string>

const std::string unk = "unknown";
const std::string clone_prefix = "clone-";

// -- interface --
class Animal {
    std::string a_type = "";
    std::string a_name = "";
    std::string a_sound = "";
public:
    Animal();   // default constructor
    Animal(const std::string & type, const std::string & name, const std::string & sound);
    Animal(const Animal &); // copy constructor
    ~Animal();  // destructor
    Animal & operator = (const Animal &); // copy operator
    void print() const;
};

// -- implementation --
Animal::Animal() : a_type(unk), a_name(unk), a_sound(unk) {
    puts("default constructor");
}

Animal::Animal(const std::string & type, const std::string & name, const std::string & sound)
: a_type(type), a_name(name), a_sound(sound) {
    puts("constructor with arguments");
}

Animal::Animal(const Animal & a) {
    puts("copy constructor");
    a_name = clone_prefix + a.a_name;
    a_type = a.a_type;
    a_sound = a.a_sound;
}

Animal::~Animal() {
    printf("destructor: %s the %s\n", a_name.c_str(), a_type.c_str());
    a_name = "";
    a_type = "";
    a_sound = "";

}

Animal & Animal::operator = (const Animal & o) {
    puts("assignment operator");
    if(this != &o) {
        a_name = clone_prefix + o.a_name;
        a_type = o.a_type;
        a_sound = o.a_sound;
    }
    return *this;
}

void Animal::print () const {
    printf("%s the %s says %s\n", a_name.c_str(), a_type.c_str(), a_sound.c_str());
}

int main() {
    
    Animal a;
    a.print();
    
    const Animal b("goat", "bob", "baah");
    b.print();
    
    const Animal c = b;
   // const Animal c (b);
    
    c.print();
    
    a = c;
    a.print();
    
    puts("end of main");
    return 0;
}
C++ 复制构造函数

评论

2赞 user17732522 7/7/2022
哪个部分让你感到困惑? (通常)通过构造函数调用以初始值设定项 () 作为参数进行初始化。重载解析选择复制构造函数。const Animal c = b;cb
2赞 Goswin von Brederlow 7/7/2022
你想知道为什么它不是作业吗?因为这就是语言的定义。 等效于 。Animal c = b;Animal c{b};
2赞 Sam Varshavchik 7/7/2022
C++ 中有几件事具有替代语法。它们在逻辑上是等价的,可以互换。这是另一个等价于 .c=b;c.operator=(b)
4赞 Eljay 7/7/2022
我认为你的困惑是有道理的。情况比你目前所看到的要深。如果你有兴趣并且有一个小时的时间可以消磨时间,必读尼古拉·乔苏蒂斯(Nicolai Josuttis)的《C++初始化的噩梦》。
4赞 user4581301 7/7/2022
IOCCC是人们在喝多了之后发出的声音。当你认为获胜的代码看起来像你喝多了之后写的东西时,这恰恰是对的。

答: 暂无答案