[英]Cannot access private member declared in class 'CObject'
I am trying to create a copy constructor for a CStringArray. 我正在尝试为CStringArray创建一个副本构造函数。 once the code is compiled, visual studio gave me this error : Cannot access private member declared in class 'CObject'
一旦代码被编译,Visual Studio就给我这个错误:无法访问在类'CObject'中声明的私有成员
in example.h I have declared the variable: 在example.h中,我声明了变量:
list<CStringArray>EqptListPpiedsOptions;
in example.cpp 在example.cpp中
I use this as my copy constructor : 我将其用作复制构造函数:
example::example(const example &data) {
list<CStringArray>::const_iterator itr = data.EqptListPpiedsOptions.begin();
while (itr != data.EqptListPpiedsOptions.end()) {
this->EqptListPpiedsOptions.push_back(*itr);
itr++;
}
}
How can I correctly use the copy constructor CStringArray List ? 如何正确使用复制构造函数CStringArray List?
Any help will be appreciated. 任何帮助将不胜感激。
There's not much to say without knowing what CStringArray
or EqptListPpiedsOptions
are. 在不知道什么是
CStringArray
或EqptListPpiedsOptions
情况下没有太多要说的。 But just as an aside: 但顺便说一句:
If you're in C++11land or later, you can use auto
instead of tediously spelling out the type, so 如果您使用的是C ++ 11land或更高版本,则可以使用
auto
而不是单调地拼写类型,因此
list<CStringArray>::const_iterator itr = data.EqptListPpiedsOptions.cbegin();
becomes 变成
auto itr = data.EqptListPpiedsOptions.cbegin();
(Note also in C++11 you use cbegin()
and cend()
for const_iterator
s. (另请注意,C ++ 11使用
cbegin()
和cend()
为const_iterator
秒。
And you can simplify further using ranged- for
: 您还可以进一步简化使用ranged-
for
:
for (const auto &itr : data.EqptListPpiedsOptions) {
this->EqptListPpiedsOptions.push_back(itr);
}
Here's a working example showing a copy constructor can access private data members of another instance of the class: 这是一个工作示例,该示例显示副本构造函数可以访问该类的另一个实例的私有数据成员:
#include <initializer_list>
#include <iostream>
#include <list>
class Example {
public:
Example() = default;
Example(std::initializer_list<int> li) : li_(li) {}
Example(const Example &data);
void print() {
for (const auto i : li_) {
std::cout << i << ", ";
}
}
private:
std::list<int> li_;
};
Example::Example(const Example &data) {
for (const auto &i : data.li_) {
this->li_.push_back(i);
}
}
int main() {
Example foo{5, 4, 3, 2, 1};
Example bar;
bar = foo; // call copy constructor and move foo.li_ to bar.li_
bar.print();
}
Although in this example, the default copy constructor works just as well, so there's no need to specify a new one. 尽管在此示例中,默认的复制构造函数也可以正常工作,所以无需指定新的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.