为什么我可以在未定义的函数和类中使用双冒号,但不能在变量中使用??
例子:
#include <iostream>
using namespace std;
class Person{
public:
int age;
string name();
};
int Person::age = 10; //It outputs an error
string Person::name(){ //It doesn't
return "n";
}
Run Code Online (Sandbox Code Playgroud)
为什么我可以在未定义的函数和类中使用双冒号,但不能在变量中使用??
age是一个实例字段,它存在于内存中的多个位置 - 每个Person存在一个。
我现在将详细介绍::运算符的作用、如何使用它以及static类成员与实例成员的比较:
::操作:所述::(该范围分辨率操作者)具有在C ++中的多种用途:
如果您熟悉 Java、C# 或 JavaScript,那么它可以被比作点解引用或“导航操作符” .(例如namespace.Class.Method().Result)——除了 C++ 使用不同的操作符进行不同类型的导航和解引用:
.是成员访问运算符,类似于 C - 它仅适用于“对象值”和引用 ( foo&),而不适用于指针 ( foo*)。->是指针类型的另一个成员访问运算符,请注意该运算符可以被覆盖但不能被覆盖.(覆盖->是有风险的,但如果正确完成,它会改善智能指针库的人体工程学)。::是范围解析运算符- 它有几个不同的用途:
.导航包和命名空间,C ++的用途::,例如:using std::time。::std,如果您正在编写已经在命名空间中的代码,这很方便。static成员(静态方法或字段),但也可以是enum class(范围枚举)值之类的项目(例如SomeEnumClass::value_name)virtual方法实现时选择特定的基方法:当被覆盖的方法需要调用超类中的基实现时使用它 - C++ 没有C# 和 Java(分别)具有的单数base或super关键字,因为C++允许多重继承,所以必须指定具体的父类名:如何从派生类函数调用父类函数?无论如何,在您的情况下,您似乎对实例和静态成员的实际含义感到困惑,所以这里有一个说明:
class Person {
public:
int height; // each Person has their own height, so this is an instance member
static int averageHeight; // but an individual Person doesn't have an "average height" - but a single average-height value can be used for all Persons, so this is a shared ("static") value.
int getAverageHeight() { // this is an instance method, btw
return Person::averageHeight; // use `Person::` to unambiguously reference a static member of `Person`
}
Person()
: height(0) {
// instance members should be initialized in the constructor!
}
}
// This will create an array of 10 people (10 different object instances).
// Each Person object (an instance) will have its own `height` in memory
Person* multiplePeople = new Person[10];
// btw, you probably should use `std::array` with an initializer instead:
// array<Person,10> multiplePeople{}; // <-- like this
// This sets a value to the `staticField` member, which exists only once in memory, that is, all Person instances share the same value for this member...
Person::averageHeight = 175; // 175cm
// ...for example:
assert( 175 == multiplePeople[3]->getAverageHeight() );
assert( 175 == multiplePeople[6]->getAverageHeight() );
// However instance members can have different values for each instance:
multiplePeople[3]->height = 170;
multiplePeople[6]->height = 180;
// Btw `height` is initialized to 0 in each Person's constructor.
assert( 170 != multiplePeople[0]->height );
assert( 180 != multiplePeople[7]->height );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3118 次 |
| 最近记录: |