I was thinking about creating copy constructor for A
class but I'm not sure which approach to take.
class A {
private:
int a;
int b;
public:
A() { a = 0; b = 0; }
int gA() { return a; }
int gB() { return b; }
};
class B {
private:
int *x;
int *y;
public:
B() { x = 0 y = 0; }
int* X() { return x; }
int* Y() { return y; }
};
Your code has two problems:
There is no way of creating an Alpha
object or a Beta
object that is not all zero, so Alpha a1 = aBetaObject;
cannot do anything useful.
The get methods are not const
, so they can't be used in const
contexts. You should ensure const correctness by marking the get methods as const
.
You need to fix these two problems first.
Then, to support Alpha a1 = aBetaObject;
and a2 = aBetaObject;
, you need to provide a constructor to allow Alpha
to be initialized with Beta
.
Alpha(const Beta& beta)
:a{*beta.getX()}, b{*beta.getY()}
{
}
Note that this is undefined behavior when beta.x
or beta.y
is a null pointer. You can make a check:
Alpha(const Beta& beta)
{
if (beta.getX() && beta.getY()) {
a = *beta.getX();
b = *beta.getY();
} else {
throw std::invalid_argument{"blah blah blah"};
}
}
Or you can make sure that beta.x
and beta.y
are never null, which doesn't seem to be the case here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.