且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于const修饰符的两个问题

更新时间:2023-02-25 18:09:29

int main()

{

int val1 = 0,val4 = Demo :: VALUE;

演示演示;

demo.Read(& val1,0); //绝对可以

demo.Read(const_cast< int *>(& val2),1); //这里是const_cast安全吗?


}



对不起,主要方法应该是:
>
int main()

{

int val1 = 0,val4 = Demo :: VALUE;

演示演示;

demo.Read(& val1,0); //绝对可以

demo.Read(const_cast< int *>(& Demo :: VALUE),1); //是const_cast安全

这里?

demo.Read(& val2,1); //使用这个?

}




Allen写道:

1.为什么不能将静态成员函数声明为const?


class Demo

{

public:

static int method()const; //错误!!

};



因为const函数意味着函数不会改变

实例,所以它被调用。静态函数没有实例,所以不能完全改变它......它只是简单地说它们是没有意义的,因为它没有意义。




Allen写道:

int main()

{

int val1 = 0,val4 = Demo :: VALUE;

演示演示;

demo.Read(& val1,0); //绝对可以

demo.Read(const_cast< int *>(& val2),1); //这里是const_cast安全吗?


}



对不起,主要方法应该是:
>
int main()

{

int val1 = 0,val4 = Demo :: VALUE;

演示演示;

demo.Read(& val1,0); //绝对可以

demo.Read(const_cast< int *>(& Demo :: VALUE),1); //是const_cast安全

在这里?



绝对不是。


1. why can not static member function be declared as const?

class Demo
{
public:
static int method() const; // error!!
};

2. is this kind of const_cast usage secure?

class Demo
{
public:
static const int VALUE = 12;

void Read(int* pValue, int offset)
{
if (offset < 0 || offset >= 2)
return;
value[offset] = *pValue;
}

private:
int value[2];
};

int main()
{
int val1 = 0, val4 = Demo::VALUE;
Demo demo;
demo.Read(&val1, 0); // absolutely ok
demo.Read(const_cast<int*>(&val2), 1); // is const_cast secure here?
}

int main()
{
int val1 = 0, val4 = Demo::VALUE;
Demo demo;
demo.Read(&val1, 0); // absolutely ok
demo.Read(const_cast<int*>(&val2), 1); // is const_cast secure here?

}

Sorry, main method should be:

int main()
{
int val1 = 0, val4 = Demo::VALUE;
Demo demo;
demo.Read(&val1, 0); // absolutely ok
demo.Read(const_cast<int*>(&Demo::VALUE), 1); // is const_cast secure
here?
demo.Read(&val2, 1); // use this?
}



Allen wrote:
1. why can not static member function be declared as const?

class Demo
{
public:
static int method() const; // error!!
};

Because a const function means that the function will not change the
instance it is called on. Static functions have no instance so can''t
exactly change it...it just plain makes no sense for them to be const
as it''s meaningless.



Allen wrote:
int main()
{
int val1 = 0, val4 = Demo::VALUE;
Demo demo;
demo.Read(&val1, 0); // absolutely ok
demo.Read(const_cast<int*>(&val2), 1); // is const_cast secure here?

}


Sorry, main method should be:

int main()
{
int val1 = 0, val4 = Demo::VALUE;
Demo demo;
demo.Read(&val1, 0); // absolutely ok
demo.Read(const_cast<int*>(&Demo::VALUE), 1); // is const_cast secure
here?

Absolutely not.