类定义
Rectangle.h
class Rectangle{
private:
double length;
double wideth;
public:
Rectangle();//自定义构造函数后,默认的构造函数就没有了
void setLength(double length);
void setWideth(double wideth);
double getLength();
double getWideth();
double getArea();
};
Rectangle.cpp
Rectangle::Rectangle(){
this->length = 2;
this->wideth = 2;
}
void Rectangle::setLength(double length){
this->length = length;
}
void Rectangle::setWideth(double wideth){
this->wideth = wideth;
}
double Rectangle::getLength(){
return this->length;
}
double Rectangle::getWideth(){
return this->wideth;
}
double Rectangle::getArea(){
return this->length * this->wideth;
}
静态定义对象
//main.cpp
int main(int argc, char *argv[])
{
[class] Rectangle angle;
}
- 静态定义局部对象,main函数结束时,系统自动销毁对象
- 调用无参数的构造函数写法:
[class] Rectangle angle;(正确)
[class] Rectangle angle();(错误) - 定义angle对象时,如果没有自定义构造函数,系统会调用默认的构造函数(没做任何事情),其angle对象中的成员变量为随机值;如果有自定义构造函数,系统会调用自定义构造函数,如上Rectangle::Rectangle(),其中对length,wideth进行了初始化,其成员变量值为随机值。
动态定义对象
//main.cpp
int main(int argc, char *argv[])
{
[class] Rectangle* angle1 = new Rectangle(10, 20);
//Rectangle* angle1 = new Rectangle;
//Rectangle* angle1 = new Rectangle();
cout << angle1->getArea() << endl;
}
- 动态定义对象,main函数结束时,对象依然存在,需要程序员自己销毁对象
- 调用无参数的构造函数写法:
[class] Rectangle* angle1 = new Rectangle;(正确)
[class] Rectangle* angle1 = new Rectangle();(正确) - 定义angle对象时,如果没有自定义构造函数,系统会调用默认的构造函数,并且系统会自动初始化成员成员变量为默认值;如果有自定义构造函数,系统会调用自定义构造函数,如上Rectangle::Rectangle(),其中对length,wideth进行了初始化,并且系统会自动初始化成员成员变量为默认值。
如果设计一个类时,没有显示声明定义构造函数、析构函数、复制(拷贝)构造函数、赋值运算符重构、地址运算符,则编译器会自动生成。
浅拷贝:源对象与拷贝对象成员所指向空间相同
深拷贝:源对象与拷贝对象成员所指向空间不同,但内容相同。
//main.cpp
int main(int argc, char *argv[])
{
Rectangle angle1(1,2);//构造函数
Rectangle angle2(angle1);//复制构造函数
Rectangle angle3;
angle3 = angle2;//赋值运算符重载
}
本文介绍了一个简单的矩形类定义,包括成员变量及构造函数等,演示了静态与动态方式创建对象的过程,以及复制构造函数和赋值运算符重载的概念。

1507

被折叠的 条评论
为什么被折叠?



