C++在类中所有的成员函数外定义变量,在成员函数内再次定义变量时,变量会受到怎样的影响?如:namespace obs { phyExercise::phyExercise():m_readiness(0),m_ndirection(0),m_npole_position(100000),count_number_(0.0000000f),start(0.0f),count(0){ } phyExercise::~phyExercise() { } clock_t start; clock_t end; void phyExercise::front_count(const obs_joint_t pt1, const obs_joint_t pt2, const int chin) { int diff = m_npole_position- chin; static clock_t start;}
时间: 2024-03-29 17:34:42 浏览: 19
在成员函数内再次定义变量时,会隐藏类中所有成员函数外定义的同名变量,即成员函数内的变量会覆盖类中的同名变量。在你的代码中,成员函数front_count中的start变量会隐藏类中定义的同名变量,也就是说,front_count函数中的start只在函数内有效,不会影响到类中其他地方对start的使用。同时,成员函数内定义的变量会在执行完该函数后自动销毁,不会占用额外的空间。
相关问题
C++类的成员函数能定义静态变量吗
C++中的类成员函数可以定义静态变量。静态变量是属于类的,而不是属于某个对象的。静态变量在程序运行时只分配一次内存,所有对象共享同一份静态变量的内存,因此静态变量的值在所有对象中都是相同的。
在类的成员函数中定义静态变量时,需要在变量声明前加上static关键字。例如:
```
class MyClass {
public:
void myFunc();
static int myStaticVar;
};
void MyClass::myFunc() {
myStaticVar++; // 访问静态变量
}
int MyClass::myStaticVar = 0; // 初始化静态变量
```
在上述代码中,myStaticVar是MyClass类的静态变量。该变量在类的定义外部进行初始化,表示对静态变量进行内存分配。在myFunc()成员函数中可以直接访问myStaticVar静态变量。
静态成员变量可以在C++类的函数里定义吗
可以在类的函数里定义静态成员变量,但是需要注意以下几点:
1. 静态成员变量必须在类定义外进行初始化,否则会出现链接错误;
2. 如果在类的函数中定义静态成员变量,那么该函数必须是静态成员函数;
3. 在类的函数中定义的静态成员变量只对该函数可见,其他函数无法访问。
举个例子:
```cpp
class MyClass {
public:
static void func() {
static int count = 0; // 在静态成员函数中定义静态成员变量
count++;
std::cout << "count: " << count << std::endl;
}
};
```
在上面的例子中,`count` 是一个静态成员变量,它在静态成员函数 `func` 中被定义。由于 `count` 是静态成员变量,它将被所有 `MyClass` 的对象所共享,并且只要调用一次 `func` 函数,`count` 就会被初始化,之后每次调用 `func` 函数都会使 `count` 值增加。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)