C++入门经典-例7.5-对象的指针,函数指针调用类成员

1:指向相应对象的指针就是对象的指针,它的生明方法与其他类型一样,如下:

类名 *p;

    类的指针可以调用它所指向对象的成员。形式如下:

p->类成员;

2:代码如下:

(1)cat.h

#include <string>
using std::string;
class cat
{
public :
    string m_name;
    void sound();
    cat();//构造函数
    cat(string name);//构造函数
};
View Code

(2)cat.cpp

#include "stdafx.h"
#include "cat.h"
#include <iostream>
using std::cout;
using std::endl;
cat::cat()
{
    m_name = "小猫";
}
cat::cat(string name)
{
    m_name = name;
}
void cat::sound()
{
    cout<<"喵呜"<<endl;
}
View Code

(3)main.h

#include "stdafx.h"
#include "cat.h"
#include <iostream>
using std::cout;
using std::endl;
cat::cat()
{
    m_name = "小猫";
}
cat::cat(string name)
{
    m_name = name;
}
void cat::sound()
{
    cout<<"喵呜"<<endl;
}
View Code

运行结果:

原文地址:https://www.cnblogs.com/lovemi93/p/7551653.html