C++好心的高手帮忙解释一下这个程序里的问题吧!
来源:百度知道 编辑:UC知道 时间:2024/06/08 15:01:54
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass(int i)
{
value = i;
cout << "Constructor called of " << value << endl;
}
void Print()
{ cout << "The value is " << value << endl; }
~MyClass()
{ cout << "Destructor called of " << value << endl; }
private:
int value;
};
int main()
{
const MyClass obj(10);
obj.Print();
return 0;
}
由于定义print()的时候后面没加const,程序通不过,请教一下这里为什么要加const?它的作用在这段程序里是什么?
using namespace std;
class MyClass {
public:
MyClass(int i)
{
value = i;
cout << "Constructor called of " << value << endl;
}
void Print()
{ cout << "The value is " << value << endl; }
~MyClass()
{ cout << "Destructor called of " << value << endl; }
private:
int value;
};
int main()
{
const MyClass obj(10);
obj.Print();
return 0;
}
由于定义print()的时候后面没加const,程序通不过,请教一下这里为什么要加const?它的作用在这段程序里是什么?
因为你在main函数中把obj定义为了常对象,而常对象只能被常成员函数引用,所以必须将print()定义为常成员函数,即:
void print() const;
桥梁
const MyClass obj(10);
本来你定义的对象就是const的了
const就是把他定义为常量,程序运行中值是不可改变的..
print() const
print()
这两个函数不是一个函数,,自然编译通不过!
这样也可以,去除常对象的const属性
const_cast<MyClass&>(obj).Print();
通过对象调用类成员函数,其实传了一个隐含的参数this引用
而你通过常对象调用,传给它的隐含参数是constMyClass类型, 不是MyClass&类型
因此会报类型不一致
对象obj被申明为常量。所以运行过程中不可以改变常量的成员变量。如果调用普通的成员函数则有可能改变对象的成员变量。所以编译器不允许调用常量对象的没有const属性的成员函数。