【发布时间】:2014-01-01 19:47:24
【问题描述】:
我正在学习 C++,但我并不真正了解如何通过函数传递对象。我读到有三种方法可以做到这一点。通过值、引用和指针传递。我想我想通过引用来做?
我很确定我在通过引用传递时遇到了问题,因为我尝试在 main 中测试它而不调用函数
std::string nameInput = "Penguin";
std::string colorInput = "Black";
Animal temp(nameInput,colorInput);
zoo.addAnimal(temp);
zoo.printDatabase();
而且效果很好。但是当我尝试通过函数调用它时,我什至无法将它添加到向量中。在发布之前我尝试了 addAnimal(Animal &toAdd) 但我不确定到底发生了什么。因为我不只是将地址传递给函数吗?而不是对象动物本身。
或者也许我完全看错了方向。这就是我喜欢在这里发帖的原因,因为拥有另一双眼睛总是很好!
//Zoo.h
#include<vector>
#include<animal.h>
#ifndef ZOO_H_
#define ZOO_H_
class Zoo{
private:
std::vector<Animal> database;
public:
void addAnimal(animal toAdd);
void printDatabase();
};
#endif ZOO_H_
//Animal.h
#include<string>
#ifndef ANIMAL_H_
#define ANIMAL_H_
class Animal{
private:
std::string name;
std::string color;
public:
Animal(std::string name, std::string color);
void printInfo();
}
#endif ANIMAL_H_
//Zoo methods
void Zoo::printDatabase(){
for(std::vector<Animal>::iterator list = database.begin(); list != list.end(); list++){
(*list).printInfo();
}
}
void Zoo::addAnimal(Animal toAdd){
database.push_back(toAdd);
}
//Animal Methods
Animal::Animal(std::string inputName, std::string inputColor){
name = inputName;
color = inputColor;
}
void Animal::printInfo(){
std::cout << "Name: " << name << "\n";
std::cout << "Color: " << color >> "\n";
}
//main.cpp
int main(){
Zoo zoo;
std::string input;
do{
printMenu();
std::getline(std::cin, input);
if(!input.empty()){
decide(input, zoo);
}
}while(input != "3";
}
void printMenu(){
std::cout <<"Zoo database\n";
std::cout << "1.Add Animal \n";
std::cout << "2.Print \n";
std::cout << "3.Exit \n";
}
void decide(std::string input, Zoo zooInput){
std::string name;
std::string color;
if(input == "1"){
std::cout << "Please enter the name of the animal to add \n";
std::getline(std::cin,name);
std::cout << "Please enter the color of the animal \n";
std::getline(std::cin,color);
Animal temp(name,color);
zooInput.addAnimal(temp);
}
if(input == "2"){
zooInput.printDatabase();
}
}
【问题讨论】:
标签: c++ vector pass-by-reference