C++:如何在类中获取具有动态变量的私有属性

C++: How to get a private property with a dynamic variable in a class?

本文关键字:动态 变量 属性 获取 C++      更新时间:2023-10-16

我想创建一个简单的Car类,该类具有Car::get方法,可用于访问带有字符串的汽车私有属性,例如:

// Create Car Intance
Car myCar;
cout << myCar.get("wheels");

我的问题是我不知道如何使用动态变量指向私有属性。这是类:

// Libraries & Config
#include <iostream>
using namespace std;
// Create Car Class
class Car {
   private: 
       int wheels = 4;
       int doors = 5;
   public: 
       Car();                // constructor
       ~Car();               // deconstructor
       int get(string what); //
};
// Constructor
Car::Car(){ cout << "Car constructed." << endl; }
// Deconstructor
Car::~Car(){ cout << "Car deconstructed." << endl; }
// Get Method
int Car::get(string what){
    // === THE PROBLEM ===
    // How do I access the `wheels` property of the car class with the what argument?
    return this[what] // ??
}
// Create Car Instance
Car myCar;
cout << myCar.get("wheels");
您可以使用

std::map执行以下操作:

#include <map>
#include <string>
#include <iostream>
using namespace std;
class Car {
   private:
       std::map<std::string, int> parts = {{"wheels", 4}, {"doors", 5}};
   public:
       Car();
       ~Car();
       int get(std::string what);
};
// Constructor
Car::Car(){ std::cout << "Car constructed." << endl; }
// Deconstructor
Car::~Car(){ std::cout << "Car deconstructed." << endl; }
// Get Method
int Car::get(string what){
    return parts[what];
}
int main()
{
    // Create Car Intance
    Car myCar;
    cout << myCar.get("wheels") << 'n';
}

值得在这里阅读std::map的工作原理:http://en.cppreference.com/w/cpp/container/map

class Car {
   private: 
       int wheels = 4;    <<< This would flag an error as you cannot provide
       int doors = 5;     <<< in class initialization for non-consts.

int Car::get (string what)
{
  if( what == "wheels" )        //// check for case sensitivity...
      return wheels;
  else
      return doors;
}