10 构造函数及赋值运算
赋值运算不会创造新对象
Dot = sk
就是说Dot是一个早已存在的对象。
10.1构造函数
此处我感觉李青这边说的“创建对象时是由系统自动调用适当的构造函数……”是在糊我。
10.1.1默认构造函数
10.1.2转换构造函数
此处有修技术之嫌疑。。。用了C的string处理。。。
10.1.3构造函数的使用
1.创建对象数组
//自己试试比较好,他这个没有给样例。。。
2.创建动态对象或动态对象数组
下面第一个方框对应着上面三个黑体字
10.2析构函数
10.2.1析构函数的概念
“~”这个东西长得奇小无比
10.2.2对象构造和析构顺序
好像这个有点用的
10.3拷贝构造函数
//说的挺拗口的
最后一句话是空话。。虽说没有的话OOP就没有意义了
10.3.1浅拷贝构造——拷贝对象的基本空间的数据类型
//不续了,讲的不好。。。
顺便附上本章练习的答案,不然就像白学。
10.1(1)
include
using namespace std;
class Test
{
public:
/错误一void/ Test(int x = 0) { a = x; }
Test(const Test &t) { a = t.a/错误二/; }
~Test(/错误三析构函数不能带有参数int x/) { delete /错误五delete的是一个指针/&a; }
//冒号语法只能在构造函数中使用void Set(int x):a(x){}
int Get() { return a; }
private:
int a;
};
10.1(2)
include
using namespace std;
class A
{
public:
A(int x) { a = x; }
private:
int a;
};
class B
{
public:
//错误一a.a 在private中 B(int x = 0) { a.a = x; }
B(const B &x) { /错误二:这边访问不了a.a/ /错误三= x.a这里的a是一个A类型的对象/; }
private:
//错误四A没有 void参数构造函数
A a=1;
};
10.2(1)
include
using namespace std;
class RMB
{
public:
RMB(double x=0) {
yuan = (int)x;
jiao = (int)(x * 10) - 10 * yuan;
fen = (int)(x * 100) - 100 * yuan - 10 * jiao;
}
RMB(int x, int y, int z) {
yuan = x;
jiao = y;
fen = z;
}
void cRMB(double x = 0) {
yuan = (int)x;
jiao = (int)(x * 10) - 10 * yuan;
fen = (int)(x * 100) - 100 * yuan - 10 * jiao;
}
void cRMB(int x, int y, int z) {
yuan = x;
jiao = y;
fen = z;
}
void show(void) {
cout << yuan << “.” << jiao << fen << endl;
}
protected:
int yuan;
int jiao;
int fen;
};
(2)图片我就都不传了,抄一抄就好了
(3)-(5)
#include
#include
using namespace std;
class Employee {
public:
Employee(string x = “NoName”, string y = “NoAddress”, string z = “NoZIP”) {
name = x;
addr = y;
zip = z;
}
Employee(const char *x = “NoName”, const char *y = “NoAddress”, const char *z = “NoZIP”) {
name = x;
addr = y;
zip = z;
}
Employee(const Employee &temp) {
name = temp.name;
addr = temp.addr;
zip = temp.zip;
}
void Display(void) {
cout << “姓名 : ” << name << ” 地址 : ” << addr << ” 邮编 : ” << zip << endl;
}
void ChangeName(string temp) {
name = temp;
}
private:
string name, addr, zip;
};
int main() {
Employee s(“张 三”, “中山路 18 号”, “200020”);
Employee staff[3] = {“李四”, s, Employee(“王 五”, “中南路 100 号”)};
staff[1].ChangeName(“赵 六”);
s.Display();
for (int i = 0; i < 3; i++) {
staff[i].Display();
}
return 0;
}
/Users/zhou/CLionProjects/zyadd/cmake-build-debug/zyadd
姓名 : 张 三 地址 : 中山路 18 号 邮编 : 200020
姓名 : 李四 地址 : NoAddress 邮编 : NoZIP
姓名 : 赵 六 地址 : 中山路 18 号 邮编 : 200020
姓名 : 王 五 地址 : 中南路 100 号 邮编 : NoZIP
Process finished with exit code 0
这边的码是CLion复制出来的,就不改了,注意const……第一次写数组咋都读不进。
(6)