[英]How should I write to get '2' as output in this class?
#include <iostream>
using namespace std;
class ParentClass
{
public:
int id;
ParentClass(int id)
{
this->id = id;
}
void print()
{
cout << id << endl;
}
};
class ChildClass: public ParentClass
{
public:
int id;
ChildClass(int id): ParentClass(1)
{
this->id = id;
}
};
int main()
{
ChildClass c(2);
c.print();
return 0;
}
I run this C++ file and I get '1' as output, I want to know how should I write to get '2' as output ? 我运行此C ++文件,并得到“ 1”作为输出,我想知道如何编写以使“ 2”得到输出? Or say that how to access a redefined variable from a derived class.
或者说如何从派生类访问重新定义的变量。
You cannot access ChildClass::id
from ParentClass::print
. 您不能从
ParentClass::print
访问ChildClass::id
。 More generally: You cannot access members of a derived class, from a member function of the parent. 更一般而言:您不能从父级的成员函数访问派生类的成员。
You can access ChildClass::id
within the member functions of ChildClass
. 您可以访问
ChildClass::id
的成员函数内ChildClass
。
ChildClass::id
isn't a "redefined" variable. ChildClass::id
不是“重新定义”的变量。 It is a separate, unrelated variable that happens to have the same identifier, but in different scope. 它是一个独立的,不相关的变量,碰巧具有相同的标识符,但作用域不同。 There is no concept of "redefining" a member variable in a derived class, in C++.
在C ++中,没有“重新定义”派生类中的成员变量的概念。
I recommend considering, whether it makes sense for ChildClass
to have two different ids. 我建议考虑,让
ChildClass
具有两个不同的ID是否有意义。
Your ChildClass is doing some wrong or discutable stuff: 您的ChildClass正在做一些错误或可争论的事情:
1. it's "shadowing" the int id member of ParentClass 1.“遮蔽” ParentClass的int id成员
2. it's calling the ParentClass constructor passing 1 (instead of "id") 2.调用传递1的ParentClass构造函数(而不是“ id”)
3. it's using assignements in constructors instead of initializer lists 3.它在构造函数而不是初始化列表中使用赋值
4. ParentClass::id visibility may be decreased from public to protected or private. 4. ParentClass :: id可见性可能会从公共降低到受保护或私有。
Try the following modified code: 尝试以下修改的代码:
#include <iostream>
class ParentClass
{
public:
int id;
ParentClass(int id) : id(id) {}
void print()
{
std::cout << id << std::endl;
}
};
class ChildClass: public ParentClass
{
public:
ChildClass(int id): ParentClass(id) {}
};
int main()
{
ChildClass c(2);
c.print();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.