[英]Issue in accessing member variables
#include<iostream>
class A {
int a, b;
public:
void setdata(int x, int y) { a = x; b = y; }
void showdata() { std::cout << a << b; }
};
class B : public A { };
int main() {
A a1;
B b1;
a1.setdata(5, 4);
a1.showdata();
b1.showdata();
}
I just want to print the values of the a
and b
members using the b1
object of class B
, as it can access the member functions of class A
since class B
has public inheritance of class A
. 我只想使用类
B
的b1
对象打印a
和b
成员的值,因为它可以访问类A
的成员函数,因为类B
具有类A
公共继承。 But, I am getting garbage values when I try to print the values of a
and b
using b1
. 但是,当我尝试使用
b1
打印a
和b
值时,我得到了垃圾值。
Can someone explain why this is happening and how to fix it? 有人可以解释为什么会这样,以及如何解决它?
a1
and b1
are completely separate object instances in memory. a1
和b1
是内存中完全独立的对象实例。 They have their own copies of the a
and b
members in memory. 他们在记忆中有自己的
a
和b
成员副本。 They have nothing to do with each other at all. 他们根本没有任何关系。 Whatever you do to
a1
does not affect b1
at all, and vice versa. 无论你对
a1
做什么都不会影响b1
,反之亦然。
You are initializing the members of a1
only, you are not initializing the members of b1
at all. 您只是初始化
a1
的成员,而不是初始化b1
的成员。 That is why you are seeing garbage when you try to print out the members of b1
. 这就是为什么当你试图打印
b1
的成员时你看到垃圾。
Before calling b1.showdata()
, you need to call b1.setdata()
to initialize b1
's members, eg: 在调用
b1.showdata()
之前,需要调用b1.setdata()
来初始化b1
的成员,例如:
int main() {
A a1;
B b1;
a1.setdata(5, 4);
a1.showdata();
b1.setdata(1, 2); // <-- add this!
b1.showdata();
}
You should also give class A
a default constructor that initializes the members to default values, in case setdata()
is not called after construction (such as what happened in your case), eg: 您还应该为
class A
一个默认构造函数,该构造函数将成员初始化为默认值,以防在构造后未调用setdata()
(例如在您的情况下发生的情况),例如:
class A {
int a, b;
public:
A() : a(0), b(0) {} // <-- add this!
void setdata(int x, int y) { a = x; b = y; }
void showdata() { std::cout << a << b; }
};
Alternatively, you might consider giving class A
and class B
a constructor that takes values as input, eg: 或者,您可以考虑为
class A
和class B
class A
一个将值作为输入的构造函数,例如:
class A {
int a, b;
public:
A() : a(0), b(0) {}
A(int x, int y) : a(x), b(y) {} // <-- add this!
void setdata(int x, int y) { a = x; b = y; }
void showdata() { std::cout << a << b; }
};
class B : public A {
public:
B() : A() {}
B(int x, int y) : A(x, y) {}
};
/* or simpler:
class B : public A {
public:
using A::A; // <-- inherit all constructors
};
*/
int main() {
A a1(5, 4);
B b1(1, 2);
a1.showdata();
b1.showdata();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.