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

How to access object's member variable's dereferenced value

提问人:Reno 提问时间:10/29/2019 最后编辑:Vlad from MoscowReno 更新时间:10/29/2019 访问量:73

问:

我正在尝试复制传递给复制构造函数的对象。我想访问传递给此函数的对象的成员变量的取消引用值,但收到错误“expected unqualified-id before '(' token int *c = new int(other.(*pa));

该类定义如下:

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));
 }

Main 定义如下:

Foo first(1,2);
Foo second(first); 
C++ 指针 初始化 复制构造函数

评论


答:

5赞 Vlad from Moscow 10/29/2019 #1

复制构造函数可能如下所示

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

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

评论

0赞 Reno 10/29/2019
你定义构造函数的方式和 Foo::Foo(int a, int b) { int *x = new int(a); int *y = new int(b); }
0赞 Martin York 10/29/2019
@Reno 像 Vlad 一样,使用初始值设定项列表是初始化成员变量的首选方法。对于指针,结果是相同的,但对于任何具有构造函数的对象,差异可能非常不同。
0赞 Peter 10/29/2019
@Reno - 一个关键的区别是 Vlad 的方法会起作用(实际上初始化 s 成员),而你的方法不会(因为它分配给自动存储持续时间的变量,这些变量在构造函数完成时不复存在,而不是 的成员)。FooFoo
0赞 Vlad from Moscow 10/29/2019
@Reno 在这个构造函数中 Foo::Foo(int a, int b) { int *x = new int(a); int *y = new int(b); 您声明局部变量 x 和 y,它们在退出构造函数后不会被 laive。
1赞 Vlad from Moscow 10/29/2019
@Reno 在构造函数的主体中,使用了赋值运算符。一般来说,你应该更喜欢使用我展示的 mem-initializers。
0赞 Krishna Prasad P 10/29/2019 #2

将值分配给对象成员。

Foo::Foo(const Foo& other) {
    this->a = new int(other.(*a));
    this->b = new int(other.(*b));
 }

评论

0赞 Martin York 10/29/2019
在几个方面没有。我会在它被其他人否决之前修复。1:不要使用 2:星星不去那里(即 d 引用本地对象)。3:使用初始值设定项列表。4:使用需要指针而不是点this*athisthis->a
0赞 Peter 10/29/2019
和 的用法无效 - 即编译器需要将该用法诊断为错误 - 因为是指针,而不是引用。this.athis.bthis