2015级C++第9周程序阅读 类和指针

简介: 阅读程序,写出程序的运行结果并理解其运行机制。 (1)#include <iostream>using namespace std;class A{public: A(){cout<<"A";} ~A(){cout<<"~A";}};class B{ A *p;public: B()

阅读程序,写出程序的运行结果并理解其运行机制。
(1)

#include <iostream>
using namespace std;
class A
{
public:
    A(){cout<<"A";}
    ~A(){cout<<"~A";}
};

class B
{
    A *p;
public:
    B()
    {
        cout<<"B";
        p=new A();
    }
    ~B()
    {
        cout<<"~B";
        delete p;
    }
};
int main()
{
    B obj;
    return 0;
}

(2)

#include <iostream>
using namespace std;
class MyClass
{
public:
    MyClass(int x=0):i(x){cout<<"C"<<i;}
    ~MyClass(){cout<<"D"<<i;}
    void SetValue(int val){i=val;}
    int GetVal(){return i;}
private:
    int i;
};
int main()
{
    MyClass *p[3];
    int i;
    for (i=0; i<3; i++)
    {
        p[i]=new MyClass(i);
        p[i]->SetValue(p[i]->GetVal()*2);
    }
    for (i=0; i<3; i++)
        delete p[i];
    cout<<endl;
    return 0;
}

(3)

#include <iostream>
using namespace std;
class AA
{
public:
    AA(int i,int j) 
    {
        A=i;
        B=j;
        cout<<"Constructor\n";
    }
    AA(AA &obj) 
    {
        A=obj.A+1;
        B=obj.B+2;
        cout<<"Copy_Constructor\n";
    }
    ~AA() {
        cout<<"Destructor\n";
    }
    void print()
    {
        cout<<"A="<<A<<",B="<<B<<endl;
    }
private:
    int A,B;
};
int main()
{
    AA a1(2,3);
    AA a2(a1);
    a2.print();
    AA *pa=new AA(5,6);
    pa->print();
    delete pa;
    return 0;
}
目录
相关文章
|
4天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
19 0
|
4天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
2天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
2天前
|
C++
【C++11(三)】智能指针详解--RAII思想&循环引用问题
【C++11(三)】智能指针详解--RAII思想&循环引用问题
|
2天前
|
人工智能 C++
【重学C++】【指针】轻松理解常量指针和指针常量
【重学C++】【指针】轻松理解常量指针和指针常量
9 0
|
2天前
|
存储 人工智能 C++
【重学C++】【指针】详解让人迷茫的指针数组和数组指针
【重学C++】【指针】详解让人迷茫的指针数组和数组指针
25 1
|
2天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
7天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
8天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”