将const函数分配给另一个const函数 [英] Assign a const function to another const function
问题描述
如何将const函数分配给类
的const成员函数,类似于以下示例:
我尝试过:
< pre> class test
{
test();
const int y1(char i)
{
cout<<一世;
}
}
const int y2(char i);
test :: test()
{
y2(char i)=& y1;
}
由于您的y1
未访问任何内容test
的成员然后你可以将它修改为static
并写上
#include < iostream >
使用 命名空间标准;
const void (* y2)( char i);
class test
{
static const void y1( char i)
{
cout<< i<< \ n;
}
public :
test();
};
test :: test()
{
y2 =& y1;
}
int main()
{
test t;
y2(' F');
}
普通(非静态)方法的相应代码是
< pre lang =C ++> #include < < span class =code-leadattribute> iostream >
使用 namespace std;
class test;
const void (test :: * y2)( char i);
class test
{
const void y1( char i)
{
cout<< i<< \ n;
}
public :
test();
};
test :: test()
{
y2 =& test :: y1;
}
int main()
{
test t;
(t。* y2)(' F');
}
请注意,在这两种情况下,代码虽然正常工作,却毫无意义。
该代码没有多大意义。您已将y1
声明为const int
,但它不会返回任何内容。在test
构造函数中,您尝试对不可赋值的名称进行赋值。您需要使y2
一个函数指针来实现您想要的效果。
您无法提供左侧的函数赋值:它不是可修改的左值
,除非函数返回引用:
IBM Knowledge Center [ ^ ]:以下对象类型的左值不可修改左值:
数组类型
不完整类型
const限定类型
结构或联合类型,其中一个成员被限定为const类型
因为这些左值不可修改,它们不能出现在赋值语句的左侧
how can I assign a const function to a const member function of class
similar to the following example:
What I have tried:
<pre>class test { test(); const int y1(char i) { cout<< i; } } const int y2(char i); test::test() { y2(char i) = &y1; }
Since youry1
doesn't access any member of thetest
then you may modify it to bestatic
and write
#include <iostream> using namespace std; const void (*y2)(char i); class test { static const void y1(char i) { cout << i << "\n"; } public: test(); }; test::test() { y2 = &y1; } int main() { test t; y2('F'); }
The corresponding code for an ordinary (non static) method would be
#include <iostream> using namespace std; class test; const void (test::*y2)(char i); class test { const void y1(char i) { cout << i << "\n"; } public: test(); }; test::test() { y2 = &test::y1; } int main() { test t; (t.*y2)('F'); }
Please note, in both cases the code, though working, is pretty meaningless.
That code does not make much sense. You have declaredy1
asconst int
, but it does not return anything. In yourtest
constructor you are trying to make an assignment to a non-assignable name. You would need to makey2
a function pointer to achieve what you want.
You cannot provide a function of the left hand side of an assignment: it is not a modifiablelvalue
unless the function returns a reference:
Lvalues of the following object types are not modifiable lvalues:
An array type An incomplete type A const-qualified type A structure or union type with one of its members qualified as a const type
Because these lvalues are not modifiable, they cannot appear on the left side of an assignment statement
这篇关于将const函数分配给另一个const函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!