pointers - 无法将对象转换为指针 C++

标签 pointers c++11

我整夜未眠试图解决这个问题(我现在是早上 7 点...)。

我在将实例化对象的地址设置为指针时遇到问题。这是主要功能:

#include "position_vector.h"
int main(){
    PositionVector res = PositionVector(10);
    PositionVector * ptr;
    ptr = &res;                   // <--- WHERE IT BREAKS
}

h 文件“position_vector.h”的精简版:

#include<iostream>

typedef uint32_t word_t;
class PositionVector {
    public:
        word_t * vec;
/*some other member variables */
        PositionVector();
        PositionVector(size_t len);
        PositionVector & operator & ();
        PositionVector & operator !();
        ~PositionVector();

/*some other member functions*/
        void resize(size_t len);
};

我有另一个 cpp 文件,它定义了类中的所有方法。

这是一些更大的代码集的一部分,但这是失败的编译:

g++-4.9 -std=c++11 -Werror -Wall -Wextra -g -Isrc -ggdb  -c -o bin/main.o src/main.cpp

失败并出现错误:

g++-4.9 -std=c++11 -Werror -Wall -Wextra -g -Isrc -ggdb  -c -o bin/main.o src/main.cpp
src/main.cpp: In function ‘int main()’:
src/main.cpp:27:9: error: cannot convert ‘PositionVector’ to ‘PositionVector*’ in assignment
     ptr = &res;
         ^

我一定是错过了一些非常基本的东西,但我刚刚熬了一夜,我不得不跑去上类……所以我真的不能再好好思考了。

最佳答案

你在你的类中重载了operator&:

class PositionVector {
        // ...
        PositionVector & operator & ();
};

当您尝试获取地址时,编译器会调用您的重载成员函数,该函数返回一个 PositionVector&。这不能分配给 PositionVector*,因此会出现错误。

关于pointers - 无法将对象转换为指针 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026584/

相关文章:

c - 理解指向指针数组的指针作为函数中的参数

c++ - 为什么 std::accumulate 对于标准数组会有这样的行为?

c++ - 重铸空指针容器

c++ - C++11 中的固定长度可变参数包

c - 数组、指针和Sizeof关系

c - 为什么函数指针有用?

c++ - 将对非指针成员变量的引用作为指针返回可以吗?

c++ - 在 C++ 中引用 Sub Array 2D

c++ - is_standard_layout 有什么用?

c++ - 来自 stdint.h 的快速类型的溢出行为