为什么在将对象作为参数传递时不调用我的自定义构造函数?
Why my custom constructor is not called when an object is passed as a parameter?
我有以下代码:
struct Entity {
Entity() {
std::cout << "[Entity] constructed\n";
}
~Entity() {
std::cout << "[Entity] destructed\n";
}
void Operation(void) {
std::cout << "[Entity] operation\n";
}
};
void funcCpy(Entity ent) {
ent.Operation();
}
int main() {
Entity e1;
funcCpy(e1);
}
这是输出:
[Entity] constructed
[Entity] operation
[Entity] destructed
[Entity] destructed
我希望我的函数使用自定义构造函数,所以输出如下所示:
[Entity] constructed
[Entity] operation
[Entity] constructed
[Entity] destructed
[Entity] destructed
为什么会这样?我怎样才能改用我的自定义构造函数?
谢谢:)
https://en.cppreference.com/w/cpp/language/copy_constructor
对象作为参数将调用class
的复制构造函数
我有以下代码:
struct Entity {
Entity() {
std::cout << "[Entity] constructed\n";
}
~Entity() {
std::cout << "[Entity] destructed\n";
}
void Operation(void) {
std::cout << "[Entity] operation\n";
}
};
void funcCpy(Entity ent) {
ent.Operation();
}
int main() {
Entity e1;
funcCpy(e1);
}
这是输出:
[Entity] constructed
[Entity] operation
[Entity] destructed
[Entity] destructed
我希望我的函数使用自定义构造函数,所以输出如下所示:
[Entity] constructed
[Entity] operation
[Entity] constructed
[Entity] destructed
[Entity] destructed
为什么会这样?我怎样才能改用我的自定义构造函数?
谢谢:)
https://en.cppreference.com/w/cpp/language/copy_constructor
对象作为参数将调用class
的复制构造函数