第01节:不可变对象、不可变类;避免多次声明
Date1.h
class Date
{
public:
Date(int newYear, int newMonth, int newDay);
//Date(int , int , int );
int getYear();
void setYear(int newYear);
private:
int year;
int month;
int day;
};
Date1.cpp
#include "Date1.h"
Date::Date(int newYear, int newMonth, int newDay)
{
year = newYear;
month = newMonth;
day = newDay;
}
int Date::getYear()
{
return year;
}
void Date::setYear(int newYear)
{
year = newYear;
}
Person1.h
#include "Date1.h"
class Person
{
public:
Person(int id, int year, int month, int day);
Person(Person &);//拷贝构造函数
int getId();
Date * getBirthDate();
private:
int id;
Date *birthDate;
};
Person1.cpp
#include "Person1.h"
Person::Person(int id, int year, int month, int day)
{
this -> id = id;
birthDate = new Date(year, month, day);
}
Person :: Person(Person &person)
{
id = Person.id;
Date *p = person.getBirthDate();
birthDate = new Date(*p);
}
int Person::getId()
{
return id;
}
Date * Person::getBirthDate()
{
return birthDate; // Return the pointer of the object
}
TestPerson1.cpp
#include <iostream>
#include "Person1.h"
#include "Date1.h" // Person1.h已经包含Date1.h 所以这里重复定义
using namespace std;
int main()
{
Person person(111223333, 1970, 5, 3);
Date *pDate = person.getBirthDate();
pDate -> setYear(2010);
cout << person.getBirthDate() -> getYear() << endl;
return 0;
}
解决方案1
#ifndef DATE1_H
#define DATE1_H
class Date
{
public:
Date(int newYear, int newMonth, int newDay);
//Date(int , int , int );
int getYear();
void setYear(int newYear);
private:
int year;
int month;
int day;
};
#endif
解决方案2
#pragma once
class Date
{
public:
Date(int newYear, int newMonth, int newDay);
//Date(int , int , int );
int getYear();
void setYear(int newYear);
private:
int year;
int month;
int day;
};
U05S01 - 不可变对象与Thread-safe
什么是 thread-safe?
不可变对象一定是 thread-safe 的吗?为什么?
答:1、Thread-safe:在多线程环境下,多个线程在访问共享数据时,为了保证该数据的安全而做出的一种承诺或者机制;
2、不可变对象本身有两层含义,一个是共享的数据(如果有)是只读的,另一个是与生俱来的线程安全性。可以说不可变对象是天生Thread-safe;(by m15522962525)
第02节:实例成员与静态成员
static 关键字将sq 限定在fun中,main函数无法调用
静态变量在静态区 所有共有而实例变量在栈区
Circle5.h
#ifndef CIRCLE_H
#define CIRCLE_H
class Circle
{
public:
Circle();
Circle(double);
double getArea();
double getRadius();
void setRadius(double);
static int getNumberOfObjects