【发布时间】:2017-06-07 21:37:00
【问题描述】:
我试图了解引用在 c++ 中是如何工作的,所以我制作了几个包含两个不同对象的文件。一个是动物,另一个是动物园管理员。我的目标是将动物的引用传递给动物园管理员并让动物园管理员更改动物的名称,并且仍然反映在原始动物对象中。这是如何使用引用完成的?这是我正在使用的文件。
源.cpp
#include <iostream>
#include <string>
#include "Animal.h"
#include "zookeeper.h"
using namespace std;
int main() {
Animal animal;
Animal& animalRef = animal;
printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());
Zookeeper aZookeeper = Zookeeper(animalRef);
aZookeeper.changeMyAnimalsName("Fred");
printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());
//Keep cmd window open
int j;
cin >> j;
return 0;
}
动物.h
#pragma once
#include <string>
using namespace std;
class Animal {
string name = "";
int height = 0;
public:
string getName() { return name; }
int getHeight() { return height; }
void setName(string n) { name = n; }
void setHeight(int h) { height = h; }
};
动物园管理员.cpp
#include "zookeeper.h"
using namespace std;
Zookeeper::Zookeeper(Animal& a) {
_myAnimal = a;
}
void Zookeeper::changeMyAnimalsName(string newName) {
_myAnimal.setName(newName);
}
动物园管理员.h
#pragma once
#include "Animal.h"
class Zookeeper {
Animal _myAnimal;
public:
Zookeeper(Animal& a);
void changeMyAnimalsName(std::string newName);
};
【问题讨论】:
-
引用与文件无关,所以如果你想研究它们是如何工作的,请将所有代码放在一个文件中。
-
在
Zookeeper构造函数中执行_myAnimal = a;时,您正在制作副本,因为_myAnimal不是参考。 -
Animal& _myAnimal;(注意与号)和Zookeeper::Zookeeper(Animal& a) : _myAnimal(a) {} -
@IgorTandetnik 把它放在一个答案中。
-
@Barmar 这是订单吗?
标签: c++ string function oop reference