是的,我知道這聽起來很奇怪,但我正在尋找一種方法來覆寫間接運算子以回傳另一個類物件。讓我更好地解釋一下:
在main.cpp我得到了
MyInt *V = new MyInt[10];
(*V)[3]=10;
但我想擁有它:
MyInt *V = new MyInt[10];
V[3]=10;
在MyInt.h 中,我使用了一個包裝器來捕獲和洗掉 MyInt 類的方括號,然后多載“=”運算子。那是因為我需要一個可以存盤向量的類以及其中的使用計數器。更多細節在這里。
MyInt.h
wrapper operator[] ( std::size_t i ) { return wrapper( *this, i ) ; }
作業流程是“MyInt::wrapper::operator="。現在它可以作業了,但我想擺脫 (*V)。是否可以通過多載間接運算子以回傳一個可以傳遞給“wrapper::operator=”的包裝器物件來洗掉它?我在想類似的事情:
MyInt& operator*(){
return wrapper(*this)
}
但它不起作用,我明白了"error: invalid initialization of non-const reference of type ‘MyInt&’ from an rvalue of type ‘test::wrapper’"。我知道間接運算子應該回傳相同的類,但我真的需要這樣。有什么建議嗎?提前致謝。
uj5u.com熱心網友回復:
注意:此答案是在 OP 問題為:
我想擁有它:
MyInt V = new MyInt[10]; V[3]=10;
如果有人對此解決方案感興趣,我會留下這個答案。
#include <cstddef>
class MyInt {
public:
MyInt() = default;
MyInt(MyInt* d) : data(d) {} // constructor taking a `MyInt*`
// ... rule of 5 implementation needed here ...
MyInt& operator[](size_t idx) { return data[idx]; }
MyInt& operator=(int) { return *this; }
private:
MyInt* data = nullptr;
};
int main() {
MyInt V = new MyInt[10];
V[3]=10;
}
請注意,無法V知道有多少元素data指向。
uj5u.com熱心網友回復:
在指向您之前的問題的鏈接以及您在那里添加的要求之后,V[3]是未定義的行為。
new []您已經更改了回傳指向單個物件的指標的含義。
您需要完全重新考慮您的設計,以便有 10 個MyInt物件V可以指向。
struct MyCounts
{
int num_read = 0;
int num_write = 0;
};
class MyInt
{
int value;
MyCounts * counts;
static void* operator new[](size_t n){
void * ptr = malloc(sizeof(MyCounts) n * sizeof(MyInt));
MyCounts * counts = new (ptr) MyCounts;
ptr = static_cast<void *>(counts 1);
for (size_t i = 0; i < n; i, ptr = sizeof(MyInt)) {
new (ptr) MyInt{ counts };
}
return static_cast<void *>(counts 1);
}
static void* operator delete[](void* ptr, size_t n){
for (MyInt * last = reinterpret_cast<MyInt *>(ptr) n; --last != ptr; ) {
last->~MyInt();
}
ptr -= sizeof(MyCounts);
reinterpret_cast<MyCounts *>(ptr)->~MyCounts();
free(ptr);
}
public:
MyInt& operator=(int i) { value = i; counts->num_write; return *this; }
operator int() const { counts->num_read; return value; }
};
uj5u.com熱心網友回復:
我想擁有它:
MyInt* V = new MyInt[10]; V[3]=10;
您需要MyInt實作一個operator=int 來“寫入”它,并實作一個轉換運算子來“讀取”它:
#include <iostream>
struct MyInt
{
int value;
MyInt& operator=(int v) { value = v; return *this; }
operator int() const { return value; };
};
int main()
{
MyInt *V = new MyInt[10];
V[3]=10;
std::cout << V[3] << '\n';
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/516829.html
標籤:C 指针重载间接
上一篇:指標的合適算術型別是什么?
下一篇:如何在C中的函式中傳遞二維陣列?
