【发布时间】:2010-09-10 10:29:31
【问题描述】:
这是Previous Question的跟进
它变得非常复杂,所以我开始一个新线程以使我的观点更清楚。(不想删除以前的线程,因为其他提供有价值反馈的人不会失去他们获得的声誉点数)
更新的代码:(符合并有效)
#include <iostream>
using std::cout;
class Test {
public:
Test(){ }
int foo (const int) const;
int foo (int );
};
int main ()
{
Test obj;
int variable=0;
int output;
do{
output=obj.foo(3); // Call the const function
cout<<"output::"<<output<<std::endl;
output=obj.foo(variable); // Want to make it call the non const function
cout<<"output::"<<output<<std::endl;
variable++;
usleep (2000000);
}while(1);
}
int Test::foo(int a)
{
cout<<"NON CONST"<<std::endl;
a++;
return a;
}
int Test::foo (const int a) const
{
cout<<"CONST"<<std::endl;
return a;
}
输出(我得到):
NON CONST
output::4
NON CONST
output::1
NON CONST
output::4
NON CONST
output::2
NON CONST
output::4
NON CONST
output::3
NON CONST
output::4
NON CONST
output::4
NON CONST
output::4
NON CONST
output::5
输出(我想要/想到的)
CONST
output::3
NON CONST
output::1
CONST
output::3
NON CONST
output::2
CONST
output::3
NON CONST
output::3
CONST
output::3
NON CONST
output::4
CONST
output::3
NON CONST
output::5
希望我能更好地提出我的问题。我知道其他方法可以做到这一点。但这可能吗?
【问题讨论】:
-
嗯,这是我第一次看到有人在实际代码中使用 do-while。
-
不知道这是否实用..我把它当作脑筋急转弯并试图让我的脑袋绕开它..除了弄脏我们的手还有什么其他的学习方式;)跨度>
-
我不明白这不是您之前问题的重复。由于
int foo(int);和int foo(const int);是相同的函数签名,如果您在类声明中使用int foo(int);和int foo(int) const;这两个签名,您的问题会更清楚。
标签: c++ class overloading