#include <string>
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
class Text{
public:
void printconst(void) const
{cout<<"hello"<<endl;}
void print(void)
{cout<<"hello"<<endl;}
private:
int k;
};
Text *a;
int main(void)
{
a = new Text();
a->print();
return 0;
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ -o main main.cc
pateo@pateo-B86N53X:~/work/study$ ./main
hello
网上帖子转的太多,一个帖子能被转很多次,但是它们却从来没验证,那个例子带代码完全拷贝下来都运行不起来,呵呵,我就遇到过,下面是我找到的然后改了后才成功的
#include <string>
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
class Text{
public:
Text(){};
void printconst(void) const
{cout<<"hello"<<endl;}
void print(void)
{cout<<"hello"<<endl;}
private:
int k;
};
const Text text;
int main(void)
{
text.printconst();
return 0;
}
输出:
pateo@pateo-B86N53X:~/work/study$ ./main
hello
#include <string>
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
class Text{
public:
Text(){};
void printconst(void) const
{cout<<"hello"<<endl;}
void print(void)
{cout<<"hello"<<endl;}
private:
int k;
};
const Text text;
int main(void)
{
text.print();
return 0;
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ -o main main.cc
main.cc: In function ‘int main()’:
main.cc:27: error: passing ‘const Text’ as ‘this’ argument of ‘void Text::print()’ discards qualifiers
pateo@pateo-B86N53X:~/work/study$
说明:
const对象只能访问const成员函数,而非const对象可以访问任意的成员函数,包括const成员函数.
const对象只能调用const成员函数。
const对象的值不能被修改,在const成员函数中修改const对象数据成员的值是语法错误
const函数中调用非const成员函数是语法错误
const对象的成员是不可修改的,然而const对象通过指针维护的对象却是可以修改的.
c. const成员函数不可以修改对象的数据,不管对象是否具有const性质.它在编译时,以是否修改成员数据为依据,进行检查.
#include <string>
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
class R
{
public:
R(int r1, int r2) { R1=r1; R2=r2; }
void print();
void print() const;
private:
int R1, R2;
};
void R::print()
{
cout<<R1<<R2<<endl;
}
void R::print() const
{
cout<<R1<<R2<<endl;
}
int main()
{
R a(5, 4);
a.print();
const R b(20, 52);
b.print();
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ -o main main.cc
pateo@pateo-B86N53X:~/work/study$ ./main
54
2052