您的位置:首页 > 编程语言 > C语言/C++

深度探索c++对象模型(6)

2017-09-26 16:11 211 查看

类里面返回类型不同的重载方法

class Foo
{
public:
Foo();
const int val();
int val();
private:
int _val;
};


我是用的编译器vs2015会报这样的错误
无法重载仅含返回类型不同的函数


当仅需读
_val
时,调用
const int val();
当需要更改
_val
时,调用
int val();
,而现在由于C++不支持这种情况,那麽我们只能采取折衷的方案,第一种方法是,在读写的地方都使用
int val();
,对于仅需要读的地方,这样做破坏了程序的本意;第二种做法是在仅读的地方,调用
const int val();
,这样的话,在需要写的地方,就必须要强制类型转换,如:

Foo test;
Foo *val = (Foo *)&test.val();


那有没有一种方法是可以同时支持这种定义的呢?

答案是有的,不过让人感觉很邪恶

#define GET_DATA() \
public:\
const int val();\
int val();
class Foo {
GET_DATA()
private:
int _val;
};


不过我最近在测试时发现,这种做法在vs2015上不可行了。

但是不能放弃是吧,所以又有了这种做法 ,这种思路可以学习,但是在类里面实现的时候碰到了一些问题。

然后还是不死心啊,所有就找啊找,终于又找到了一种方案

class My
{
public:
int getInt() { return 1; }
char getChar() { return 'x'; }
class Proxy
{
My* myOwner;
public
Proxy(My* owner) : myOwner(owner) {}
operator int() const
{
return myOwner->getInt();
}
operator char() const
{
return myOwner->getChar();
}
};
Proxy get(My* i) { return Proxy(i); }
};


还有这种方案

class My
{
public:
void get(int, int&);
void get(int, char&);
}


placement operator new语义

对于placement
operator new()
, 它的第一个函数参数必须是
std::size_t
, 表示申请的内存的大小

void * operator new (std::size_t) throw(std::bad_alloc);    // 标准版本
void * operator new (std::size_t, const std::nothrow_t &) throw(); // placement 版本


在用户自定义空间上构建对象, 是placement new的本意, 它也被做到C++标准中, 作为default placement:

void * operator new (std::size_t, void * p) throw() { return p ; }


相应的 placement new expression 使用起来就是这样:

void *buffer = malloc(sizeof(ClassA));
ClassA *ptr = new(buffer)ClassA();


实际上就是

operator new (sizeof(ClassA), this);


由于创建对象时,operator new只能通过new关键字隐式调用,无法通过命名空间限定调用的版本,所以一旦在类中定义了operator new的重载版本,所有类外定义的operator new重载都会失效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: