我想创建一个简单的Car类,它有一个Car::get方法,可以用字符串访问car的私有属性,例如:
// 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");发布于 2015-01-01 07:22:46
您可以使用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
发布于 2015-01-01 07:13:40
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;
}https://stackoverflow.com/questions/27728946
复制相似问题