首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++:如何在类中获得具有动态变量的私有属性?

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

Stack Overflow用户
提问于 2015-01-01 07:05:47
回答 2查看 828关注 0票数 1

我想创建一个简单的Car类,它有一个Car::get方法,可以用字符串访问car的私有属性,例如:

代码语言:javascript
复制
// Create Car Intance
Car myCar;
cout << myCar.get("wheels");

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

代码语言:javascript
复制
// 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");
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-01 07:22:46

您可以使用std::map进行类似的操作。

代码语言:javascript
复制
#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

票数 2
EN

Stack Overflow用户

发布于 2015-01-01 07:13:40

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27728946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档