It would be ok to define a class like this (ignore its implmentation):
class MyEngine {
private:
int* params;
int param_len;
public:
void set_params(int* _params, int _len);
float get_result(); // relies on `distance` member
float distance; // people can modify this
};
However, if using vector
, assume it implicitly includes <iterator>
which contains std::distance
, how do compiler distinguish std::distance
and distance
member? (Or will it cause un-expected crash when run?). Say, the function get_result()
relies distance
member value.
#include <vector>
using namespace std;
class MyEngine {
private:
vector<int> params;
public:
void set_params(int* _params, int _len);
float get_result(); // relies on `distance` member
float distance; // people can modify this
};
update
As people mentioned, using namespace std
is bad practice; however, there are still people writing code with using namespace std
, and if we are collaborate with them, using their code, is there any concreate example that demonstrate the badness of using namespace std
, expecially severe run error? This, would be my real purpose.
There is an answer, saying distinguish the two distance
by type. Let's just try this snippet:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iterator>
using namespace std;
class MyEngine {
private:
vector<int> params;
float* distance; // people can modify this
int len;
public:
void setup();
};
void MyEngine::setup()
{
len = 100;
distance = (float*)malloc(sizeof(float)*len);
for(int i=0; i<len; i++) {
distance[0] = len - i;
params.push_back(len-i);
}
int num = distance(params.begin(), params.end());
printf("distance is: %d
", num);
}
int main(){
MyEngine engine;
int len = 10;
engine.setup();
return 0;
}
Which, would cause compile error saying:
main.cpp:25:23: error: called object type 'float *' is not a function or function pointer
int num = distance(params.begin(), params.end());
~~~~~~~~^
1 error generated.
Demonstrates that it can't distinguish the two distance
from their types.
question from:
https://stackoverflow.com/questions/65901849/can-i-use-distance-as-my-class-member-variable-name 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…