我正在尝试复制传递给复制构造函数的对象。我想访问传递给此函数的对象的成员变量的取消引用值,但出现错误“'(' 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/