首先,如果我在问题标题中没有使用正确的术语,我深表歉意。这是完全可能的。我开始学习 C++,我承认我在引用和拷贝方面遇到了非常困难的时间。引用我下面的代码,我有以下问题:
这是我的代码:
主文件
#include "stdafx.h"
#include <iostream>
#include "Plan.h"
#include "Carrier.h"
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<Plan> plans;
for (int i = 0; i < 4; ++i) {
Plan p(i);
plans.push_back(p);
}
Carrier c(5);
for(std::vector<Plan>::iterator it = plans.begin(); it != plans.end(); ++it) {
//my question is about the line directly below this comment
c.add(*it);
}
return 0;
}
计划.h
#pragma once
class Plan
{
private:
int id;
public:
Plan(int id);
};
计划.cpp
#include "Plan.h"
Plan::Plan(int i)
{
id = i;
}
运营商.h
#pragma once
#include <vector>
class Plan;
class Carrier
{
private:
int id;
std::vector<Plan> plans;
public:
Carrier(int i);
void add(Plan p);
};
运营商.cpp
#include "Carrier.h"
#include "Plan.h"
Carrier::Carrier(int i) {
id = i;
}
void Carrier::add(Plan p) {
plans.push_back(p);
}
最佳答案
(1) 由于 Carrier::add
不通过引用获取其参数,因此传递了一个拷贝。要让它引用,请将其签名更改为
void Carrier::add(Plan const &p);
(2) 当你做
push_back
时,无论你是通过引用还是通过值/拷贝传递 Plan
都会创建一个拷贝;这是 std::vector
(以及所有其他标准容器)语义的一部分。复制构造函数由编译器自动生成。(3)我不是VC++用户,但是编译器会生成的拷贝构造函数等价于
Plan::Plan(Plan const &other)
: id(other.id) // there's only one member,
// but other members would be treated the same
{}
在空的正文中,您可以添加一个打印语句,指示调用了复制构造函数,但这不会防水;在某些情况下,允许 C++ 执行复制省略优化,这意味着跳过实际复制。
关于c++ - 理解 C++ 中的引用和拷贝的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5653168/