玩命加载中 . . .

C++类/友元


一个简单的Human类

#include <iostream>
using namespace std;

class Human
{
public:
    Human();    // 默认构造函数
    Human(string name, int age);    // 重载构造函数
    void setName(string name);
    void setAge(int age);
    string getName();
    int getAge();
    void Introduce();
private:
    string _name;
    int _age;
    string _gender;
};

// 重载构造函数
Human::Human(string name, int age) {
    this->_name = name;
    this->_age = age;
}

void Human::setName(string name) {
    this->_name = name;
}

void Human::setAge(int age) {
    this->_age = age;
}

string Human::getName() {
    return this->_name;
}

int Human::getAge() {
    return this->_age;
}

void Human::Introduce() {
    cout << "I'm " << this->getName() << ", and I'm " << this->getAge() << " years old." << endl;
}

int main(int argc, char const *argv[])
{
    Human kavin("kavin", 23);
    kavin.setAge(34);
    kavin.Introduce();
    Human* jack = new Human("jack", 12);
    jack->Introduce();
    return 0;
}
I'm kavin, and I'm 34 years old.
I'm jack, and I'm 12 years old.

友元

声明友元函数或友元类,就可以访问类里面的私有变量

class Human
{
public:
    friend void disp(const Human& person);
};

void disp(const Human& person) {
    cout << person._age << endl;
}

int main(int argc, char const *argv[])
{
    Human kavin("kavin", 23);
    disp(kavin);
    return 0;
}

class Human
{
public:
    friend class Boys;
};

class Boys
{
public:
    static void dispName(const Human& person) {
        cout << person._name << endl;   //可以使用类里面的私有变量
    }
};

int main(int argc, char const *argv[])
{
    Human kavin("kavin", 23);
    Boys::dispName(kavin);
    return 0;
}
kavin

一个简单的Circle类

pi是一个常量

#include <iostream> 
#include <string> 
using namespace std; 

class Circle
{
public:
    Circle(int radius) : _radius(radius) {
        this->_perimeter = 2 * this->pi * this->_radius;
        this->_area = this->pi * this->_radius * this->_radius;
    }
    void info();
private:
    int _radius;
    double _perimeter;
    double _area;
    const double pi = 3.14159;
};


void Circle::info() {
    cout << this->_perimeter << endl;
    cout << this->_area << endl;
}

int main(int argc, char const *argv[])
{
    Circle first(6);
    first.info();
    return 0;
}
37.6991
113.097

如果要声明为static,要在类外面定义

class Circle{
    static const double pi;         //类里面声明
};
const double Circle::pi = 3.14159;  //类外面定义


文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录