C++:如何在类中获取具有动态变量的私有属性
C++: How to get a private property with a dynamic variable in a class?
我想创建一个简单的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;
}
相关文章:
- 如果非动态变量被指针引用,何时超出范围?
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- C++ 卷曲后动态变量
- 动态变量 cpp 编译
- 将删除运算符放置在何处以进行动态变量
- cpp 中的析构函数是否自动调用?即使析构函数没有提及非动态变量,它们也会被删除吗?
- C++动态变量和未定义内存之间的差异
- 动态变量名称构建,连接
- XML文件中的动态变量和函数调用
- 动态变量上的c++MACRO未声明标识符
- 内存泄漏递归传递动态变量
- 获取具有动态变量的结构的大小
- 创建动态变量
- C++:如何在类中获取具有动态变量的私有属性
- 基于 txt 文件的动态变量
- C++:使用宏字符串将项目转换为动态变量的简单方法
- 通过引用传递动态变量的指针
- 静态与堆栈动态变量的访问效率
- 指针、动态变量C++
- 来自c++指针的c#动态变量