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

标签 c++ pointers initialization copy-constructor

我正在尝试复制传递给复制构造函数的对象。我想访问传递给此函数的对象的成员变量的取消引用值,但出现错误“'(' token int *c = new int(other.(*pa)) 之前的预期不合格 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); 

最佳答案

复制构造函数看起来像

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

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

关于c++ - 如何访问对象的成员变量解引用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58606195/

相关文章:

c++ - 我如何将 .h 文件中的代码实现到 main.cpp 文件中?

c++ - 如何强制库使用自定义 std::allocator?

c++ - boost::spirit 指针属性是否用 nullptr 初始化?

C# 6.0 默认初始化

c++ - 命名空间中常量结构、类和数组的初始化

c++ - 如何在声明时将对象插入到 std::map 中

std::map 的 C++ 返回值引用

c++ - 如何从 C++ 中的整数缓冲区中提取 4 个字节的整数

c++ - 返回指针的地址

c++ - 输入结构体中数组的大小