如何访问对象的成员变量的解引用值

问题描述 投票:0回答:1

我正在尝试复制传递给复制构造函数的对象。我想访问传递给此函数的对象的成员变量的解引用值,但遇到错误“在'('令牌int * c = new int(other。(* pa))之前出现预期的unqualified-id;

该类已定义:

class Foo {
Public:
   int *a, *b;
   Foo(const Foo &); //copy constructor
}

我的功能已定义:

Foo::Foo(const Foo& other) {
    int* c = new int(other.(*a));
    int* d = new int(other.(*b));
 }

主定义:

Foo first(1,2);
Foo second(first); 
c++ pointers initialization copy-constructor
1个回答
4
投票

复制构造函数可以看起来像

Foo::Foo(const Foo& other) : a( new int( *other.a ) ), b( new int( *other.b ) )
{
}

这里是示范节目

#include <iostream>

class Foo {
public:
   int *a, *b;

   Foo( int x, int y ) : a( new int( x ) ), b( new int( y ) )
   {
   }

   Foo( const Foo &other  ) : a( new int( *other.a ) ), b( new int( *other.b ) )
   {
   }
};

int main() 
{
    Foo first(1,2);
    Foo second(first); 

    std::cout << *first.a << ", " << *first.b << '\n';
    std::cout << *second.a << ", " << *second.b << '\n';

    return 0;
}

其输出为

1, 2
1, 2

[所有其他特殊成员函数,例如我希望您自己定义的析构函数。

© www.soinside.com 2019 - 2024. All rights reserved.