#include<iostream>
using namespace std;
int count_nr;
class a {
a(const a& b) { count_nr++; cout << "1"; };
a(int r = 233) { count_nr++; cout << "2"; };
~a() { count_nr--; cout << "0"; };
};
int main()
{
a B, C; C = B; C = { 555 }; cout << count_nr;
}
程序错误原因 class类时没有加public,则这种情况下构造和析构函数都为私有(注意:若没有自定义构造函数与析构函数,在默认情况下,构造函数与析构函数为共有),主函数无法直接调用私有成员,无法定义B与C。
#include<iostream>
using namespace std;
int count_nr;
class a {
public:
a(const a& b) { count_nr++; cout << "1"; };
a(int r = 233) { count_nr++; cout << "2"; };
~a() { count_nr--; cout << "0"; };
};
int main()
{
a B, C;
cout <<endl;
C = B;
cout << endl;
C = { 555 };
cout << endl;
}
若加上public,则输出结果为
分析:主函数第一行新建了两个对象B,C。自动调用构造函数a(int r = 233) ;输出22
第二行把C赋值给B,未调用a中函数。
第三行往C中赋值555,调用函数a(int r = 233) ;且语句结束时自动调用析构函数。
在程序结束时,清除对象B与C,自动调用析构函数两次。
若主函数第一行为 a B, C(B);则输出为21,C(B)调用拷贝构造函数a(const a& b);未调用析构函数。
#include<iostream>
using namespace std;
int count_nr;
class a {
public:
//a(const a& b) { count_nr++; cout << "1"; };
a(int r = 233) { count_nr++; cout << "2"; };
~a() { count_nr--; cout << "0"; };
};
int main()
{
a* B = new a;
cout << endl;
delete B;
cout << endl;
cout << count_nr;
}
主函数 a* B = new a;
动态分配一个a的内存空间,并将其首地址赋值给指针变量B。
输出为2 0 0
第一行调用了构造函数
注意:单纯定义一个指针变量时,并不会调用构造函数.example:a* B;
只有当B被分配到内存空间时,才会调用析构函数。example:B = new a;
delete会自动调用析构函数。
若不加delete则主函数结束时不会自动调用析构函数。
若上面看明白,则下面这个很好懂
#include<iostream>
using namespace std;
int count_nr;
class a {
public:
a(const a& b) { count_nr++; cout << "1"; };
a(int r = 233) { count_nr++; cout << "2"; };
~a() { count_nr--; cout << "0"; };
};
int main()
{
a B, C;
C = B;
C = { 555 };
cout << count_nr;
}
输出为2220200
故不作注释
其它:
友元函数函数并不是类的成员函数。
#include<iostream>
using namespace std;
int count_nr;
class A {
static int n;
public:
A() { n = 1; }
A(int num) { n = num; }
void printf() { cout << n;}
};
int A::n = 2;
void main()
{
A a, b(3);
a.printf();
b.printf();
}
n是静态成员,先初始化n为2,此时再新建一个对象a,n的值为1,2被1覆盖,新建一个对象b,
n的值更新为3,2的值被3覆盖,此时之前所有n的值都改为3。故输出为33。
由于作者水平有限,在写解析时,难免会出现错误。望读者及时指出,谢谢。