jeudi 28 juillet 2022

How can I set class member variable correctly from vector in C++

I'm trying to set a class member variable from STL vector in C++.

But it doesn't work the way I want it to. The variable doesn't change, The variable is the same like before.

Am I programming in the wrong way?

Here's the code.

#include <iostream>
#include <vector>
using namespace std;

class Test {
private:
  std::string name;

public:
  Test();
  Test(std::string p_name);
  std::string getName();
  void setName(std::string p_name);
};

Test::Test() { name = ""; }

Test::Test(std::string p_name) : name(p_name) {}

std::string Test::getName() { return name; }

void Test::setName(std::string p_name) { name = p_name; }

int main() {
  // Initializing vector with values
  vector<Test> tests;

  for (size_t i = 0; i < 10; i++) {
    tests.push_back(Test());
  }

  for (Test test : tests) {
    cout << test.getName() << endl;
    test.setName("a");
  }

  for (Test test : tests) {
    cout << test.getName() << endl;
  }

  return 0;
}

This is the result:

> ./main




















> 

Why It doesn't work, and how to fix it?

Aucun commentaire:

Enregistrer un commentaire