在通话时挑选const与非const成员函数

在通话时挑选const与非const成员函数

本文介绍了在通话时挑选const与非const成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



大家好,


请在下面的代码中查看问题...


谢谢!

Dave

#include< iostream>


使用命名空间std;


class foo

{

public:

foo(int d):data(d){}

void print()const {cout<< " const的" << endl;}

void print(){cout<< "非const" << endl;}


私人:

int数据;

};


int main()

{

foo a(42);


//下面的调用调用非const打印();

//我想要调用const print()!

// a.print();


//这是一种方法。是否有更优雅的方式?

//制作const不在我的问题范围内!

static_cast< const foo>(a).print();


返回0;

}


Hello all,

Please see the question in the code below...

Thanks!
Dave
#include <iostream>

using namespace std;

class foo
{
public:
foo(int d) : data(d) {}
void print() const {cout << "const" << endl;}
void print() {cout << "non-const" << endl;}

private:
int data;
};

int main()
{
foo a(42);

// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();

// Here''s one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<const foo>(a).print();

return 0;
}

推荐答案









你想解决什么真正的具体问题?


-Mike



What real specific problem are you trying to solve?

-Mike





是否调用const成员函数取决于对象的constness上的
。你为什么这么想?也许

我们可以找到另一种方式。

Jonathan



Whether a const member function will be called or not depends
on the constness of the object. Why do you want that? Perhaps
we could find another way.
Jonathan


这篇关于在通话时挑选const与非const成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:05