c++中“:”的用法
时间: 2023-08-14 19:07:33 浏览: 68
在C++中,冒号“:”有多种用法,包括:
1. 在类的定义中,用于声明继承关系,如:
```
// 基类
class Animal {
public:
void eat();
};
// 派生类
class Cat : public Animal {
public:
void meow();
};
```
2. 在构造函数中,用于初始化成员变量,如:
```
class Person {
public:
Person(int age, string name) : m_age(age), m_name(name) {}
private:
int m_age;
string m_name;
};
```
3. 在命名空间中,用于指定命名空间的作用域,如:
```
namespace my_namespace {
void my_function();
}
// 调用命名空间中的函数
my_namespace::my_function();
```
4. 在条件语句中,用于分隔条件和语句块,如:
```
// if语句
if (x > 0) {
cout << "x is positive" << endl;
}
// switch语句
switch (x) {
case 0:
cout << "x is zero" << endl;
break;
case 1:
cout << "x is one" << endl;
break;
default:
cout << "x is something else" << endl;
break;
}
```
还有其他用法,但以上是比较常见的。