求教个 C++ Get 函数怎么写的问题

8次阅读

共计 520 个字符,预计需要花费 2 分钟才能阅读完成。

代码

#include
#include 
#include 

enum struct Status {kOk = 0,};

struct Student {
    std::string name;
    std::size_t age;
};

class Table {
   public:
    Table() {this->map_.insert(std::make_pair("w1", Student("li", 23)));
        this->map_.insert(std::make_pair("s2", Student("zhao", 18)));
    }

    Status Get(const std::string& key, Student* value) {*value = this->map_[key];
        return Status::kOk;
    }

    Student Get(const std::string& key) {return this->map_[key]; }

   private:
    std::unordered_map map_;
};

int main(int argc, char* argv[]) {
    Table table;

    Student stu1;
    const Status& status = table.Get("w1", &stu1);
    std::cout << stu1.name << ":" << stu1.age << std::endl;

    const Student& stu2 = table.Get("s2");
    std::cout << stu2.name << ":" << stu2.age << std::endl;
    return 0;
}

结果

li:23
zhao:18

问题

1. Status Get(const std::string& key, Student* value);
2. Student Get(const std::string& key);

在 Java/Python 等语言中,个人更喜欢第 2 种写法;但是 C++ 中,一些项目更倾向于第 1 种写法,为啥呢?这样有什么好处吗?

正文完
 0