C ++保护/公共过载 [英] C++ Protected / Public overloads
问题描述
我有一个这样的类:
class Foo
{
public:
Foo()
{
for(int i = 0; i <10; ++ i)
v.push_back(i);
};
const vector< double>& V()const {return v;};
protected:
vector< double>& V(){return v;};
private:
vector< double> v;
};
然后一段代码如下:
Foo foo;
for(int i = 0; i <(int)foo.V()。size(); ++ i)
cout< foo.V()。(i)<< endl;但是,后者引发了一个编译错误,表示 V() code> call是一个受保护的方法,而我只是试图从它读取,不修改它。
我试过以下(但没有成功)。
Foo foo;
const vector< double>& test = foo.V();
for(int i = 0; i<(int)test.size(); ++ i)
cout< test.at(i)<< endl;
非常感谢您的帮助。
=====
感谢大家的解释和解决方案!非常感谢!
解决方案这是不可能重载的返回值。当对象是非const时,将使用非const方法。可以通过以下指导编译器:
const向量< double> test = const_cast< Foo const&>(foo).V();
或者更好的解决方案是使常量方法具有不同的名称(例如: ConstV
)。或者你可以只添加这个新的方法,并留下当前的方法。这种方法在C ++ 0x标准中使用。例如,常量方法 cbegin()
和 cend()
已添加到标准容器中。
I have a class like this :
class Foo
{
public:
Foo()
{
for(int i = 0; i < 10; ++i)
v.push_back(i);
};
const vector<double>& V() const {return v;};
protected:
vector<double>& V() {return v;};
private:
vector<double> v;
};
And then a piece of code like this :
Foo foo;
for(int i = 0; i < (int) foo.V().size(); ++i)
cout << foo.V().at(i) << endl;
However, the latter raises a compilation error saying the V()
call is a protected method while i am just trying to read from it, not modify it.
I have tried the following (but without success).
Foo foo;
const vector<double>& test = foo.V();
for(int i = 0; i < (int) test.size(); ++i)
cout << test.at(i) << endl;
Many thanks for your help.
=====
Thank you all for the explanations and solutions ! It's greatly appreciated !
解决方案 It is not possible to overload on return value. Non-const method will be used when the object is non-const. It is possible to guide the compiler by:
const vector<double>& test = const_cast<Foo const&>(foo).V();
Or possibly nicer solution is to have the constant method have different name (eg.: ConstV
). Or you can just add this new method and leave the current method there. This approach is used in C++0x standard. For example constant methods cbegin()
and cend()
have been added to standard containers.
这篇关于C ++保护/公共过载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!