Sat Nov 08, 2008 11:32 pm
//file header.h
const int global_const_count = 7; // global const in header file
class CX
{
public:
CX();
const int foo(const int) const; //const member function with a const parameter and return a const
private:
const int member_const_count; //non-static const member
static const int static_member_const_count = 7; //static const member
};
//file source.cpp
#include "header.h"
const int CX::foo(const int) const //const member function implementation
{
const int i = 1; //local const
return i;
}
int main()
{
return 0;
}
//file header.h
static int global_count;
const int global_const_count = 7;
//file source1.cpp
#include "header.h"
int main()
{
return 0;
}
//file source2.cpp
#include "header.h"
//file header.h
class CX
{
public:
CX();
private:
const int member_const_count;
static const int static_member_const_count = 7;
};
//file source.cpp
#include "header.h"
CX::CX()
: member_const_count(7)
{
}
int main()
{
return 0;
}
//file header.h
class CX
{
public:
CX();
void increase();
int getCount() const;
private:
int member_ count;
};
//file source.cpp
#include <iostream>
#include "header.h"
CX::CX()
: member_count(0)
{
}
void CX::increase()
{
++member_count;
}
int CX::getCount() const
{
return member_count;
}
int main()
{
const CX cx;
//cx.increase(); //Error, cx can’t be changed.
std::cout << cx.getCount() << std::endl;
return 0;
}
//file header.h
class CX
{
public:
CX();
void increase();
int getCount() const;
private:
mutable int cache_data;
int member_count;
};
//file source.cpp
#include <iostream>
#include "header.h"
CX::CX()
: cache_data(0)
, member_count(0)
{
}
void CX::increase()
{
++member_count;
}
int CX::getCount() const
{
++cache_data;
return member_count;
}
int main()
{
const CX cx;
std::cout << cx.getCount() << std::endl;
return 0;
}
//file header.h
class CX
{
public:
CX();
void increase();
int getCount() const;
private:
mutable int cache_data;
int member_count;
};
//file source.cpp
#include <iostream>
#include "header.h"
CX::CX()
: cache_data(0)
, member_count(0)
{
}
void CX::increase()
{
++member_count;
}
int CX::getCount() const
{
++cache_data;
return member_count;
}
const int ci = 10;
int main()
{
int* pi = const_cast<int*>(&ci);
//*pi = 9;//compile OK, runtion error. Change constant ci
const CX cx;
CX* px = const_cast<CX*>(&cx);
px->increase(); //The change won’t be niticed because cx is excepted as const
std::cout << cx.getCount() << std::endl;
char* sz = "string"; //Compiler do casting
//sz[0] = 'c'; //runtime error
return 0;
}
char sz[] = "string";
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.