相关疑难解决方法(0)

使用指针复制构造函数

我最近发现,当我在一个类中有指针时,我需要指定一个Copy构造函数.

为了解这一点,我做了以下简单的代码.它编译,但在执行复制构造函数时给出了运行时错误.

我试图只复制复制对象的指针中的值,但避免分配相同的地址.

那么,这里有什么问题?

    class TRY{
        public:
        TRY();
    ~TRY();
        TRY(TRY const &);

        int *pointer;

        void setPointer(int);
    };


    void TRY::setPointer(int a){
        *pointer = a;

        return;
    }


    TRY::TRY(){}


    TRY::~TRY(){}


    TRY::TRY(TRY const & copyTRY){
        int a = *copyTRY.pointer;
        *pointer = a;
    }



    int main(){

        TRY a;
        a.setPointer(5);

        TRY b = a;

        b.setPointer(8);

        cout << "Address of object a = " << &a << endl;
        cout << "Address of object b = " << &b << endl;

        cout << "Address of a.pointer = " …
Run Code Online (Sandbox Code Playgroud)

c++ pointers copy-constructor

15
推荐指数
2
解决办法
6万
查看次数

C++ Copy构造函数+指针对象

我正在努力学习C++中的"三巨头"..我设法为"三巨头"做了非常简单的程序..但我不知道如何使用对象指针..以下是我的第一次尝试.

当我写这篇文章时,我有一个疑问......

问题

  1. 这是实现默认构造函数的正确方法吗?我不确定我是否需要它.但是我在另一个关于带有指针的复制构造函数的线程中发现的是我需要在复制构造函数中复制地址之前为该指针分配空间.
  2. 如何在复制构造函数中分配指针变量?我在Copy Constructor中编写的方式可能有误.
  3. 我是否需要为复制构造函数和operatior =实现相同的代码(返回除外)?
  4. 我是否正确地说我需要删除析构函数中的指针?

    class TreeNode
    {
    public:  
       TreeNode(); 
       TreeNode(const TreeNode& node);
       TreeNode& operator= (const TreeNode& node);
       ~TreeNode();
    private:
       string data;
       TreeNode* left;
       TreeNode* right;
       friend class MyAnotherClass;
    };
    
    Run Code Online (Sandbox Code Playgroud)

履行

TreeNode::TreeNode(){

    data = "";  

}

TreeNode::TreeNode(const TreeNode& node){
     data = node.data;

     left = new TreeNode();
     right = new TreeNode();

     left = node.left; 
     right = node.right;
}

TreeNode& TreeNode::operator= (const TreeNode& node){
     data = node.data;
     left = node.left;
     right = node.right;
     return *this;
}

TreeNode::~TreeNode(){
     delete …
Run Code Online (Sandbox Code Playgroud)

c++ rule-of-three

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×2

copy-constructor ×1

pointers ×1

rule-of-three ×1