
Dog
dog;//已有对象
doggetName()就是调用这个对象的getName成员
->是指向成员 *** 作符,左值通常是一个已有的该结构或类类型的指针。(->并不要求左值指针以分配内存,但基本上都是要分配的,为了内存读写。)如
//代码如下
#include <iostream>
using namespace std;
class Cat{
friend int getTotalWeight();
private:
static int numOfCats;
static int totalWeight;
int weight;
public:
Cat(int w){ weight=w; numOfCats++; totalWeight+=w;}
static int getNumOfCats(){
return numOfCats;
}
};
class Dog{
friend int getTotalWeight();
private:
static int totalWeight;
int weight;
public:
Dog(int w){weight =w;totalWeight+=w;}
};
int getTotalWeight(){
return Dog::totalWeight + Cat::totalWeight;
}
int Cat::numOfCats = 0;
int Cat::totalWeight = 0;
int Dog::totalWeight = 0;
int main(int argc, char argv[]) {
Cat cat1(23);
Cat cat2(123);
Cat cat3(32);
cout<<"Total number of cats: "<<Cat::getNumOfCats()<<endl;
Dog dog1(100);
Dog dog2(100);
cout<<"Total weight of all cats and dogs: "<<getTotalWeight()<<endl;
}
以上就是关于C++ 中 如何 访问类成员函数的机制,有时候看见 Dog dog; dog.getName();全部的内容,包括:C++ 中 如何 访问类成员函数的机制,有时候看见 Dog dog; dog.getName();、c++友元函数、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)